詳解Angular2中Input和Output用法及示例
對(duì)于angular2中的Input和Output可以和AngularJS中指令作類比。
Input相當(dāng)于指令的值綁定,無論是單向的(@)還是雙向的(=)。都是將父作用域的值“輸入”到子作用域中,然后子作用域進(jìn)行相關(guān)處理。
Output相當(dāng)于指令的方法綁定,子作用域觸發(fā)事件執(zhí)行響應(yīng)函數(shù),而響應(yīng)函數(shù)方法體則位于父作用域中,相當(dāng)于將事件“輸出到”父作用域中,在父作用域中處理。
看個(gè)angular2示例吧,我們定義一個(gè)子組件,獲取父作用域的數(shù)組值并以列表形式顯示,然后當(dāng)點(diǎn)擊子組件的元素時(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事件并對(duì)其進(jìn)行響應(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指令顯示。
當(dāng)點(diǎn)擊每個(gè)元素的時(shí)候觸發(fā)了click事件,執(zhí)行fireChildEvent函數(shù),該函數(shù)要將元素的index值“輸出”到父組件中進(jìn)行處理。
Output一般都是一個(gè)EventEmitter的實(shí)例,使用實(shí)例的emit方法將參數(shù)emit到父組件中,觸發(fā)父組件的childEvent事件。
然后父組件監(jiān)聽到該事件的發(fā)生,執(zhí)行對(duì)應(yīng)的處理函數(shù)getChildEvent,刪除傳遞的元素索引指向的數(shù)據(jù),同時(shí),視圖更新。
實(shí)際效果:
源碼地址:https://github.com/justforuse/angular2-demo/tree/master/angular-input-output
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
ionic3實(shí)戰(zhàn)教程之隨機(jī)布局瀑布流的實(shí)現(xiàn)方法
這篇文章主要給大家介紹了關(guān)于ionic3實(shí)戰(zhàn)教程之隨機(jī)布局瀑布流的實(shí)現(xiàn)方法,文中通過示例代碼和圖文介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2017-12-12angularjs實(shí)現(xiàn)猜數(shù)字大小功能
這篇文章主要為大家詳細(xì)介紹了angularjs實(shí)現(xiàn)猜數(shù)字大小功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-09-09Bootstrap + AngularJS 實(shí)現(xiàn)簡(jiǎn)單的數(shù)據(jù)過濾字符查找功能
這篇文章主要介紹了 Bootstrap + AngularJS 實(shí)現(xiàn)簡(jiǎn)單的數(shù)據(jù)過濾字符查找功能,代碼簡(jiǎn)單易懂,非常不錯(cuò)具有參考借鑒價(jià)值,需要的朋友可以參考下2017-07-07簡(jiǎn)單講解AngularJS的Routing路由的定義與使用
這篇文章主要介紹了AngularJS的Routing路由的定義與使用,講解了when()和otherwise()兩個(gè)相關(guān)的常用方法,需要的朋友可以參考下2016-03-03