Angular 如何监听变量变化
deepthan opened this issue · 0 comments
deepthan commented
KeyValueChanges 方法
html
<button (click)="a()">1233</button>
ts
import { KeyValueChanges, KeyValueDiffer, KeyValueDiffers } from '@angular/core';
export class Customer {
firstName: string;
favoriteColor: string;
}
export class xx {
private customerDiffer: KeyValueDiffer<string, any>;
private customer: Customer;
constructor(
private differs: KeyValueDiffers
) {
this.customer = new Customer();
this.customerDiffer = this.differs.find(this.customer).create();
}
customerChanged(changes: KeyValueChanges<string, any>) {
console.log('changes');
/* If you want to see details then use
changes.forEachRemovedItem((record) => ...);
changes.forEachAddedItem((record) => ...);
changes.forEachChangedItem((record) => ...);
*/
}
ngDoCheck(): void {
const changes = this.customerDiffer.diff(this.customer);
if (changes) {
this.customerChanged(changes);
}
}
a(){
this.customer.firstName+= "2";
}
}
使用ngModelChange
监听
<input type="text" (ngModelChange)="doSomething($event)" [ngModel]="customer.firstName">
ts
doSomething(event) {
console.log(event); // logs model value
}
如在动态表单中可使用valueChanges
监听
ngOnInit() {
this.form = this.fb.group({
// xxx
});
}
ngAfterViewInit(): void {
this.form.valueChanges.subscribe((change) => {
console.log(change)
})
}