Angular組件——父組件調用子組件方法


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);
  }

}
View Code

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>

 

本文作者starof,因知識本身在變化,作者也在不斷學習成長,文章內容也不定時更新,為避免誤導讀者,方便追根溯源,請諸位轉載注明出處:http://www.cnblogs.com/starof/p/8689908.html  有問題歡迎與我討論,共同進步。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM