一、父組件給子組件傳值 @Input
父組件給子組件不僅可以傳遞簡單的數據,還可以把父組件的方法以及整個父組件傳遞給子組件。
1、父組件調用子組件的時候傳入數據
<app-header [title]="title"></app-header>
2、子組件引入Input模塊
import {Component, Input, OnInit} from '@angular/core';
3、子組件中@Input接收父組件傳遞過來的值
export class HeaderComponent implements OnInit {
@Input()
title = '';
constructor() { }
ngOnInit() {
}
}
4、在子組件中展現title值
<h1>{{title}}</h1>
二、父組件給子組件傳方法(即子組件調用父組件的方法)
1、同傳數據一樣,在父組件模板文件調用子組件時,定義屬性
<app-header [title]="title" [run]="run"></app-header>
2、在父組件的ts文件中定義父組件的方法run
run() {
alert('我是父組件的run方法');
}
3、同理在子組件的ts文件中@Input 引入run輸入屬性,並定義調用方法
import {Component, Input, OnInit} from '@angular/core';
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
@Input()
title = '';
@Input() run;
constructor() { }
ngOnInit() {
}
getParentFun() {
// 執行父組件中的run方法
this.run();
}
}
4、子組件模板文件
<p>{{title}}</p>
<button (click)="getParentFun();">子組件執行父組件的run方法</button>
<br>
<br>
<br>
<br>
三、將父組件整個傳給子組件
明白了一、二步,這個就很容易理解,在父組件中調用子組件傳遞屬性時,屬性值直接傳遞this即可。
<app-header [parent]="this"></app-header>
其它步驟就和調用數據和方法的調用方式相同了,這樣子組件中的parent屬性就代表了父組件實例了,然後隨便咋玩。
四、父組件通過@ViewChild主動獲取子組件的數據和方法
1、定義子組件的屬性及方法:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-footer',
templateUrl: './footer.component.html',
styleUrls: ['./footer.component.css']
})
export class FooterComponent implements OnInit {
constructor() { }
public msg = '我是子組件的msg';
ngOnInit() {
}
run() {
alert('我是子組件的run方法');
}
}
2、父組件模板文件中調用子組件,並設置其id
<hr>
<p>
我是一個新聞組件
</p>
<hr>
<button (click)="getChildMsg();">獲取子組件的msg</button>
<br>
<br>
<button (click)="getChildRun();">執行子組件的run方法</button>
<br>
<br>
<br>
<br>
<br>
<br>
<app-footer #footer></app-footer>
3、父組件的控制類中通過@ViewChild 引入子組件對象
import {Component, OnInit, ViewChild} from '@angular/core';
@Component({
selector: 'app-news',
templateUrl: './news.component.html',
styleUrls: ['./news.component.css']
})
export class NewsComponent implements OnInit {
constructor() { }
@ViewChild('footer') footerEl: any; // 獲取子組件
ngOnInit() {
}
// 獲取子組件的屬性
getChildMsg() {
alert(this.footerEl.msg);
}
// 執行子組件的方法
getChildRun() {
this.footerEl.run();
}
}
四、子組件通過@Output觸發父組件的方法
1、子組件中引入Output和EventEmiter
import {Component, EventEmitter, OnInit, Output} from '@angular/core';
2、子組件中實例化EventEmiter
@Output() private outer = new EventEmitter();
3、子組件通過EventEmiter 對象outer實例廣播數據
callParentFun() {
const object: any = new Object();
object.aa = 'aa';
object.bb = 'bb';
this.outer.emit(object);
}
4、父組件調用子組件的時候,定義接收事件 outer就是子組件的EventEmiter對象outer
<app-footer #footer (outer)="formChild($event);"></app-footer>
5、父組件接收到數據會調用自己的formChild方法,這個時候父組件就能拿到子組件的數據
formChild(e) {
console.log(e);
alert(e.aa);
}