viewChild裝飾器。
父組件的模版和控制器里調用子組件的API。
1、創建一個子組件child1里面只有一個greeting方法供父組件調用。

import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-child1', templateUrl: './child1.component.html', styleUrls: ['./child1.component.css'] }) export class Child1Component implements OnInit { constructor() { } ngOnInit() { } greeting(name: string) { console.log("hello" + name); } }
2、父組件中分別在模版中用模版本地變量調用和在控制器中用ts代碼調用。
父組件寫2個<app-child>並分別指定模版本地變量
<app-child1 #child1> </app-child1> <app-child1 #child2> </app-child1>
3,在父組件控制器中聲明一個由viewChild裝飾器裝飾的變量獲得子組件的引用。
通過模版變量的名字child1找到相應的子組件並賦值給child1變量,拿到引用就可以調用子組件方法。
@ViewChild('child1') child1:Child1Component; //父組件中獲得子組件的引用 ngOnInit(){ this.child1.greeting("Tom"); }
4,在父組件模版中調用子組件方法。
在父組件模版中加一個button,點擊時去調用子組件child2的greeting方法。
<app-child1 #child1> </app-child1> <app-child1 #child2> </app-child1> <button (click)="child2.greeting('Jerry')">調用child2的greeting方法</button>