理解組件
組件是一種特殊的指令,使用更簡單的配置項來構(gòu)建基于組件的應(yīng)用程序架構(gòu)
這樣他能簡單地寫app,通過類似的web Component 或者angular2的樣式。
web Component 是一個規(guī)范。馬上就要成為標(biāo)準(zhǔn)。
應(yīng)用組件的優(yōu)點:
比普通指令配置還簡單
提供更好的默認(rèn)設(shè)置和最好的實踐
對基于組建的應(yīng)用架構(gòu)更優(yōu)化。
對angular2的升級更平滑。
不用組建的情況:
對那些在 compile或者pre-link階段要執(zhí)行操作的指令,組件不能用,因為無法到達(dá)那個階段。
如果你想定義指令的 priority,terminal,multi-element,也不能用。
組件只能通過元素標(biāo)簽觸發(fā),其他的只能用命令。
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>
相信看了本文案例你已經(jīng)掌握了方法,更多精彩請關(guān)注Gxl網(wǎng)其它相關(guān)文章!
推薦閱讀:
使用Nodejs mongoose案例解析(附代碼)
vue+axios做出禁止登陸
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com