您好,登錄后才能下訂單哦!
學(xué)過(guò)Angular的同學(xué)都知道,輸入框通過(guò)[(ngModel)]
實(shí)現(xiàn)雙向數(shù)據(jù)綁定,那么自定義組件能不能實(shí)現(xiàn)雙向數(shù)據(jù)綁定呢?答案是肯定的。
Angular中,我們常常需要通過(guò)方括號(hào)[]
和圓括號(hào)()
實(shí)現(xiàn)組件間的交互:
那么在[]
和()
的基礎(chǔ)上,如何實(shí)現(xiàn)組件的雙向數(shù)據(jù)綁定?
例子如下。
子組件:
<!--testDataBinding.component.html--> <h2>childStatus: {{childStatus}}</h2>
//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); } }
注意這里的寫(xiě)法,這是關(guān)鍵所在,輸出屬性前半部分必須與輸入屬性相同,輸入屬性可以隨意取名,輸出屬性需在輸入屬性基礎(chǔ)上加上Change,比如你的輸入屬性是myData,那么輸出屬性就必須是myDataChange。
父組件:
<!--app.component.html--> <test-binding [(childStatus)]="parentStatus"></test-binding> <h2>parentStatus: {{parentStatus}}</h2>
//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); } }
在父組件我們初始化parentStatus
為true
,并把它傳到子組件TestDataBindingComponent
。
在子組件里,5秒后我們把childStatus
設(shè)為false
,看它能不能傳到父組件。再過(guò)5秒,我們?cè)诟附M件將parentStatus
設(shè)為true
,看它能不能傳到子組件。
事實(shí)證明,子組件值變化后,父組件的值也跟著變化;父組件值變化后子組件的值也跟著變了!
我們實(shí)現(xiàn)了雙向綁定!
查看本文代碼和效果,可點(diǎn)擊這里。
以上這篇Angular自定義組件實(shí)現(xiàn)數(shù)據(jù)雙向數(shù)據(jù)綁定的實(shí)例就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。