詳解Angular2中Input和Output用法及示例
對于angular2中的Input和Output可以和AngularJS中指令作類比。
Input相當于指令的值綁定,無論是單向的(@)還是雙向的(=)。都是將父作用域的值“輸入”到子作用域中,然后子作用域進行相關(guān)處理。
Output相當于指令的方法綁定,子作用域觸發(fā)事件執(zhí)行響應(yīng)函數(shù),而響應(yīng)函數(shù)方法體則位于父作用域中,相當于將事件“輸出到”父作用域中,在父作用域中處理。
看個angular2示例吧,我們定義一個子組件,獲取父作用域的數(shù)組值并以列表形式顯示,然后當點擊子組件的元素時調(diào)用父組件的方法將該元素刪除。
//app.component.html <app-child [values]="data" (childEvent) = "getChildEvent($event)"> </app-child> //app.component.ts @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { data = [1,2,3]; getChildEvent(index){ console.log(index); this.data.splice(index,1); } }
以上是跟組件app-root的組件類及模板,可以我們把data輸入到子組件app-child中,然后接收childEvent事件并對其進行響應(yīng)。
//app-child.component.html <p *ngFor="let item of values; let i = index" (click)="fireChildEvent(i)"> {{item}} </p> //app-child.component.ts @Component({ selector: 'app-child', templateUrl: './child.component.html', styleUrls: ['./child.component.css'] }) export class ChildComponent implements OnInit { @Input() values; @Output() childEvent = new EventEmitter<any>(); constructor() { } ngOnInit() { } fireChildEvent(index){ this.childEvent.emit(index); } }
子組件定義了values接收了父組件的輸入,這里就是data值,然后使用ngFor指令顯示。
當點擊每個元素的時候觸發(fā)了click事件,執(zhí)行fireChildEvent函數(shù),該函數(shù)要將元素的index值“輸出”到父組件中進行處理。
Output一般都是一個EventEmitter的實例,使用實例的emit方法將參數(shù)emit到父組件中,觸發(fā)父組件的childEvent事件。
然后父組件監(jiān)聽到該事件的發(fā)生,執(zhí)行對應(yīng)的處理函數(shù)getChildEvent,刪除傳遞的元素索引指向的數(shù)據(jù),同時,視圖更新。
實際效果:
源碼地址:https://github.com/justforuse/angular2-demo/tree/master/angular-input-output
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
ionic3實戰(zhàn)教程之隨機布局瀑布流的實現(xiàn)方法
這篇文章主要給大家介紹了關(guān)于ionic3實戰(zhàn)教程之隨機布局瀑布流的實現(xiàn)方法,文中通過示例代碼和圖文介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧。2017-12-12Bootstrap + AngularJS 實現(xiàn)簡單的數(shù)據(jù)過濾字符查找功能
這篇文章主要介紹了 Bootstrap + AngularJS 實現(xiàn)簡單的數(shù)據(jù)過濾字符查找功能,代碼簡單易懂,非常不錯具有參考借鑒價值,需要的朋友可以參考下2017-07-07