Angular2中監聽資料更新
angular2 模型資料更新了,需要監聽資料改變,
一、實現介面Docheck,檢測頁面上所有元素資料更
-
import { Component, DoCheck } from "@angular/core";
-
export class LangListUserComponent implements DoCheck {
-
constructor(private differs: KeyValueDiffers) {
-
}
-
ngOnInit() {
-
this.objDiffer = {};
-
this.list.forEach((elt) => {
-
this.objDiffer[elt] = this.differs.find(elt).create(null);
-
});
-
}
-
ngDoCheck() {
-
this.list.forEach(elt => {
-
var objDiffer = this.objDiffer[elt];
-
var objChanges = objDiffer.diff(elt);
-
if (objChanges) {
-
objChanges.forEachChangedItem((elt) => {
-
if (elt.key === 'prop1') {
-
this.doSomethingIfProp1Change();
-
}
-
});
-
}
-
});
-
}
二、針對頁面上某個元素的資料更新做處理
1、定義模板驅動表單名
<input type="text" pInputText size="50" [formControl]="term" placeholder="輸入搜尋條件">
2、ts 檔案中新建一個表單元素物件。
colo = new FormControl(); 3、ngonInit中訂閱資料更新
this.colo.valueChanges.distinctUntilChanged().subscribe((ast) => {
//do something
})