學過Angular的同學都知道,輸入框通過[(ngModel)]實現雙向數據綁定,那么父子組件間能不能實現雙向數據綁定呢?答案是肯定的。
Angular中,我們常常需要通過方括號[]和圓括號()實現組件間的交互:

那么在[]和()的基礎上,如何實現組件的雙向數據綁定?
例子如下。
子組件:
<!--child.component.html-->
<h1>status in child: {{childStatus}}</h1>
<button (click)="toggle()">Toggle childStatus</button>
//child.component.ts
export class ChildComponent implements OnInit{
@Input() childStatus;
@Output() childStatusChange = new EventEmitter();
ngOnInit(){
}
toggle(){
this.childStatus = !this.childStatus;
this.childStatusChange.emit(this.childStatus);
}
}
注意這里的寫法,這是關鍵所在,輸出屬性必須在輸入屬性的基礎上加上‘-Change’后綴。比如你的輸入屬性是myData,那么輸出屬性就必須是myDataChange。
父組件:
<!--app.component.html-->
<test-binding [(childStatus)]="parentStatus"></test-binding>
<h1>status in parent: {{parentStatus}}</h1>
<button (click)="toggle()">Toggle parentStatus</button>
//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(){
}
toggle(){
this.parentStatus = !this.parentStatus;
}
}
在父組件我們初始化parentStatus為true,並把它傳到子組件ChildComponent。
在子組件里,通過按鈕我們可以改變childStatus的值,可以看到,子組件中的值改變的同時,父組件的值也跟着改變了。反過來,在父組件中通過按鈕改變parentStatus的值,子組件中的值同樣也跟着變化:

很簡單對不對?!
你可以在這里查看和在線編輯本文代碼,並實時查看效果!
