理解組件
組件是一種特殊的指令,使用更簡單的配置項來構建基于組件的應用程序架構
這樣他能簡單地寫app,通過類似的web Component 或者angular2的樣式。
web Component 是一個規范。馬上就要成為標準。
應用組件的優點:
比普通指令配置還簡單
提供更好的默認設置和最好的實踐
對基于組建的應用架構更優化。
對angular2的升級更平滑。
不用組建的情況:
對那些在 compile或者pre-link階段要執行操作的指令,組件不能用,因為無法到達那個階段。
如果你想定義指令的 priority,terminal,multi-element,也不能用。
組件只能通過元素標簽觸發,其他的只能用命令。
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>
相信看了本文案例你已經掌握了方法,更多精彩請關注Gxl網其它相關文章!
推薦閱讀:
webpack里腳手架優化的實現方法
vue axios請求超時如何處理
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com