gpt4 book ai didi

javascript - Angular 4 : How to watch an object for changes?

转载 作者:太空狗 更新时间:2023-10-29 16:54:45 24 4
gpt4 key购买 nike

ETA:我知道有多种方法可以查看我的表单变化。那不是我想要做的。正如标题所说,我问的是如何观察一个对象的变化。下面显示的应用程序仅用于说明目的。请回答我提出的问题。谢谢!

我有这个简单的应用程序:

import { Component, OnInit } from '@angular/core';

export class Customer {
firstName: string;
favoriteColor: string;
}

@Component({
selector: 'my-app',
template: `
<div *ngIf="customer">
<input type="text" [(ngModel)]="customer.firstName">
<input type="text" [(ngModel)]="customer.favoriteColor">
</div>
`
})
export class AppComponent implements OnInit {

private customer: Customer;

ngOnInit(): void {

this.customer = new Customer();

// TODO: how can I register a callback that will run whenever
// any property of this.customer has been changed?

}

}

注意 TODO。我需要注册一个回调,该回调将在 this.customer 的任何属性发生更改时运行。

我无法对输入使用 ngChange。我需要直接订阅模型的更改。 原因与我的用例有关,不值得在此处详述。请相信我,这不是一个选择。

这可能吗?我做了很多谷歌搜索,但我已经干涸了。

最佳答案

Angular 通常使用注入(inject)到构造函数中 KeyValueDiffers类(class)。

对于您的情况,它可能看起来像:

import { KeyValueChanges, KeyValueDiffer, KeyValueDiffers } from '@angular/core';

export class Customer {
firstName: string;
favoriteColor: string;
}

@Component({
selector: 'my-app',
templateUrl: `./app.component.html`
})
export class AppComponent {
private customerDiffer: KeyValueDiffer<string, any>;
private customer: Customer;

constructor(private differs: KeyValueDiffers) {}

ngOnInit(): void {
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);
}
}
}

Stackblitz Example

另一种选择是对要检查的属性使用 setter。

另见

关于javascript - Angular 4 : How to watch an object for changes?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46330070/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com