理解組件
組件是一種特殊的指令,使用更簡單的配置項來構(gòu)建基于組件的應(yīng)用程序架構(gòu)
這樣他能簡單地寫app,通過類似的web Component 或者angular2的樣式。
web Component 是一個規(guī)范。馬上就要成為標(biāo)準(zhǔn)。
應(yīng)用組件的優(yōu)點:
不用組建的情況:
viewChild裝飾器。
父組件的模版和控制器里調(diào)用子組件的API。
1、創(chuàng)建一個子組件child1里面只有一個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個<app-child>
并分別指定模版本地變量
<app-child1 #child1> </app-child1><app-child1 #child2> </app-child1>
3,在父組件控制器中聲明一個由viewChild裝飾器裝飾的變量獲得子組件的引用。
通過模版變量的名字child1找到相應(yīng)的子組件并賦值給child1變量,拿到引用就可以調(diào)用子組件方法。
@ViewChild('child1')child1:Child1Component; //父組件中獲得子組件的引用ngOnInit(){ this.child1.greeting("Tom");}
4,在父組件模版中調(diào)用子組件方法。
在父組件模版中加一個button,點擊時去調(diào)用子組件child2的greeting方法。
<app-child1 #child1> </app-child1><app-child1 #child2> </app-child1><button (click)="child2.greeting('Jerry')">調(diào)用child2的greeting方法</button>
總結(jié)
以上所述是小編給大家介紹的Angular父組件調(diào)用子組件的方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對武林網(wǎng)網(wǎng)站的支持!
新聞熱點
疑難解答