您好,登錄后才能下訂單哦!
本篇文章為大家展示了Angular中怎么通過父組件調(diào)用子組件,內(nèi)容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細(xì)介紹希望你能有所收獲。
1、創(chuàng)建一個(gè)子組件child1里面只有一個(gè)greeting方法供父組件調(diào)用。
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、父組件中分別在模版中用模版本地變量調(diào)用和在控制器中用ts代碼調(diào)用。
父組件寫2個(gè)<app-child>
并分別指定模版本地變量
<app-child1 #child1> </app-child1> <app-child1 #child2> </app-child1>
3,在父組件控制器中聲明一個(gè)由viewChild裝飾器裝飾的變量獲得子組件的引用。
通過模版變量的名字child1找到相應(yīng)的子組件并賦值給child1變量,拿到引用就可以調(diào)用子組件方法。
@ViewChild('child1') child1:Child1Component; //父組件中獲得子組件的引用 ngOnInit(){ this.child1.greeting("Tom"); }
4,在父組件模版中調(diào)用子組件方法。
在父組件模版中加一個(gè)button,點(diǎn)擊時(shí)去調(diào)用子組件child2的greeting方法。
<app-child1 #child1> </app-child1> <app-child1 #child2> </app-child1> <button (click)="child2.greeting('Jerry')">調(diào)用child2的greeting方法</button>
上述內(nèi)容就是Angular中怎么通過父組件調(diào)用子組件,你們學(xué)到知識(shí)或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識(shí)儲(chǔ)備,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。