# 1:@Input
步驟:
1:父組件調用子組建時傳方法
2:在子組件引入Input
3:在子組件聲明,通過Input接受父組件傳過來的方法
4:在子組件使用父組件傳過來的數據
《parent.component.html》:
<app-child [run] = " run "></app-child>
《child.component.ts》:
import { Component, OnInit,Input} from '@angular/core'; ??
... ? ...
export class HeaderComponent implement OnInit {
@Input() getDataFromChild;
public childmsg = "這是子組件的數據";
constructor() { }
ngOnInit() { }
sendParent(){ ?//子組件自己的方法
? ?this.getDataFromChild(this.childmsg); ?// 子組件調用父組件的方法
}
}
《parent.component.ts》:
import { Component, OnInit }from '@angular/core';
export class NewsComponent implements OnInit {
constructor(){}
... ? ?...
ngOnInit() { ?}
getDataFromChild(childData) {
? ? alert("這是子組件傳來的數據"+childData);
}
}
《child.component.html》:
<button (click) = "sendParent()">給父組件傳值</button>
# 2:過渡 ?-- 父組件調用子組件的方法獲取子組件的值
步驟:
1:父組件調用子組件的時候給子組件起個名字
2:父組件直接可以拿到子組件變量名下的數據
《child.component.ts》:
import { Component, OnInit} from '@angular/core';
... ? ...
export class HeaderComponent implement OnInit {
public msg="這是子組件的數據";
constructor() { }
ngOnInit() { }
childFun(){
? alert("這是子組件的方法");
}
}
《parent.component.html》:
<button (click)="childFun()">調用子組件的方法</button>
<app-child #childCom></app-child>
# 3:@ViewChild ?-- 父組件調用自己的方法獲取子組件的方法和值
步驟:
1:父組件調用子組件的時候給子組件起個名字
2:父組件引入ViewChild
3:ViewChild與子組件關聯
4:調用子組件
《child.component.ts》:
import { Component, OnInit} from '@angular/core';
... ? ...
export class HeaderComponent implement OnInit {
public msg="這是子組件的數據";
constructor() { }
ngOnInit() { }
childFun(){
alert("這是子組件的方法");
}
}
《parent.component.html》:
<button (click)="getDataFromChild()">父組件調用自己的方法獲取子組件的數據</button>
<app-child #childCom></app-child>
《parent.component.ts》:
import { Component, OnInit, ViewChild }from '@angular/core';
export class NewsComponent implements OnInit {
@ViewChild('childCom') ?cart; ? ? //定義子組件 () 里面和#** 要一致
constructor(){}
... ? ?...
ngOnInit() { ?}
getDataFromChild(childData) {
? ? this.cart.childFun(); ? ? ?//執行子組件的方法
? ? alert( this.cart.msg); ? ? //獲取子組件的數據
}
}