最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

詳解Angular2中Input和Output用法及示例

 更新時(shí)間:2017年05月21日 14:37:42   作者:justforuse  
這篇文章主要介紹了詳解Angular2中Input和Output用法及示例,對(duì)于angular2中的Input和Output可以和AngularJS中指令作類比,有興趣的可以了解一下

對(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

以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論

济宁市| 石楼县| 临海市| 大同县| 富平县| 通化市| 奉贤区| 永和县| 陇川县| 南充市| 定结县| 修文县| 蒲江县| 醴陵市| 青州市| 弋阳县| 郓城县| 石狮市| 铁岭市| 韩城市| 新巴尔虎右旗| 黄山市| 无为县| 成安县| 卓资县| 陇西县| 白银市| 广安市| 闸北区| 大化| 武隆县| 绥宁县| 正镶白旗| 闻喜县| 威信县| 抚松县| 莲花县| 赤水市| 庄浪县| 东莞市| 贞丰县|