詳解Angular2中Input和Output用法及示例
對于angular2中的Input和Output可以和AngularJS中指令作類比。
Input相當于指令的值綁定,無論是單向的(@)還是雙向的(=)。都是將父作用域的值“輸入”到子作用域中,然后子作用域進行相關(guān)處理。
Output相當于指令的方法綁定,子作用域觸發(fā)事件執(zhí)行響應函數(shù),而響應函數(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事件并對其進行響應。
//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í)行對應的處理函數(shù)getChildEvent,刪除傳遞的元素索引指向的數(shù)據(jù),同時,視圖更新。
實際效果:

源碼地址:https://github.com/justforuse/angular2-demo/tree/master/angular-input-output
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
詳解Angular中通過$location獲取地址欄的參數(shù)
這篇文章主要介紹了詳解 Angular中通過$location獲取地址欄的參數(shù),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-08-08
AngularJs ng-repeat 嵌套如何獲取外層$index
這篇文章主要介紹了AngularJs ng-repeat 嵌套如何獲取外層$index的相關(guān)資料,需要的朋友可以參考下2016-09-09
AngularJS實現(xiàn)的base64編碼與解碼功能示例
這篇文章主要介紹了AngularJS實現(xiàn)的base64編碼與解碼功能,結(jié)合實例形式分析了AngularJS字符串base64編碼與解碼操作相關(guān)實現(xiàn)技巧,需要的朋友可以參考下2018-05-05
Angular4實現(xiàn)圖片上傳預覽路徑不安全的問題解決
這篇文章主要給大家介紹了關(guān)于Angular4實現(xiàn)圖片上傳預覽路徑不安全問題的解決方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面來一起學習學習吧。2017-12-12
Angular通過angular-cli來搭建web前端項目的方法
這篇文章主要介紹了Angular通過angular-cli來搭建web前端項目的方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-07-07

