一、父傳子
-
-
在父組件html中的子組件標簽中定義自定義屬性來綁定父組件定義的信息
-
在子組件中的ts中,通過@Input來接收自定義屬性的名稱
import {Input} from '@angular/core';
@Input() info:string;
- 在子組件中的html中就能直接得到值了
-
import {Output, EventEmitter } from '@angular/core';
-
並且通過@Output實例化要傳遞向父組件的消息
@Output() private outer = new EventEmitter();
public chtofather = 'child to father';
-
給子組件添加點擊事件,點擊的時候將數據傳遞給父組件
handlerClick() {
this.outer.emit(this.chtofather)
}
<p (click)="handlerClick()"></p>
-
在父組件html中綁定自定義事件
<app-test (outer) = "handlerChild($event)"></app-test>
-
在父組件的ts中通過剛剛綁定的自定義事件中的event就可以獲取到了
handlerChild(e) {
console.log(e)
在父組件html里的子組件標簽上定義一個名字(#名字),相當於這個子組件的id名
<app-son #son ></app-son>
在父組件的ts中引入ViewChild
import { Component, ViewChild } from '@angular/core';
並使用
@ViewChild('son') son; 括號里面的名稱要與子組件標簽#后面的名稱一致。
最后就可以調用子組件的數據和方法,如果子組件中有一個數據為viewChildinfo,就可以這樣去調用
getData() {
this.mydata = this.son.viewChildinfo;
}