欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Angular自定義組件實現(xiàn)數(shù)據(jù)雙向數(shù)據(jù)綁定的實例

 更新時間:2017年12月11日 08:17:47   作者:無er不樂  
下面小編就為大家分享一篇Angular自定義組件實現(xiàn)數(shù)據(jù)雙向數(shù)據(jù)綁定的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

學(xué)過Angular的同學(xué)都知道,輸入框通過[(ngModel)]實現(xiàn)雙向數(shù)據(jù)綁定,那么自定義組件能不能實現(xiàn)雙向數(shù)據(jù)綁定呢?答案是肯定的。

Angular中,我們常常需要通過方括號[]和圓括號()實現(xiàn)組件間的交互:

那么在[]()的基礎(chǔ)上,如何實現(xiàn)組件的雙向數(shù)據(jù)綁定?

例子如下。

子組件:

<!--testDataBinding.component.html-->

<h1>childStatus: {{childStatus}}</h1>
//testDataBinding.component.ts

export class TestDataBindingComponent implements OnInit{
 @Input() childStatus;
 @Output() childStatusChange = new EventEmitter();
 ngOnInit(){
 setTimeout(()=>{
  this.childStatus = false;
  this.childStatusChange.emit(this.childStatus);
 },5000);
 }
}

注意這里的寫法,這是關(guān)鍵所在,輸出屬性前半部分必須與輸入屬性相同,輸入屬性可以隨意取名,輸出屬性需在輸入屬性基礎(chǔ)上加上Change,比如你的輸入屬性是myData,那么輸出屬性就必須是myDataChange。

父組件:

<!--app.component.html-->

<test-binding [(childStatus)]="parentStatus"></test-binding>
<h1>parentStatus: {{parentStatus}}</h1>
//app.component.ts

import { Component,OnInit } from '@angular/core';
@Component({
 selector: 'my-app',
 templateUrl: './app.component.html',
 styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
 parentStatus: boolean = true;
 ngOnInit(){
 setTimeout(()=>{
  this.parentStatus = true;
 },10000);
 }
}

在父組件我們初始化parentStatustrue,并把它傳到子組件TestDataBindingComponent

在子組件里,5秒后我們把childStatus設(shè)為false,看它能不能傳到父組件。再過5秒,我們在父組件將parentStatus設(shè)為true,看它能不能傳到子組件。

事實證明,子組件值變化后,父組件的值也跟著變化;父組件值變化后子組件的值也跟著變了!

我們實現(xiàn)了雙向綁定!

查看本文代碼和效果,可點擊這里

以上這篇Angular自定義組件實現(xiàn)數(shù)據(jù)雙向數(shù)據(jù)綁定的實例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論