在Angular2 / Typescript中,是否可以“观察”对象的字段以进行更改.
例如,假设我有一个Person类,其字段为firstName,lastName和fullName.是否可以在firstName或lastName更改时自动更新fullName?
像这样的东西:
export class Person { firstName: string= ''; lastName: string = ''; fullName: string = ''; constructor(firstName: string,lastName: string) { this.firstName.onChange(() => { this.updateFullName(); }); this.lastName.onChange(() => { this.updateFullName(); }); this.firstName = firstName; this.lastName = lastName; } updateFullName() { this.fullName = `${this.firstName} ${this.lastName}`; } }
第一种方法
原文链接:https://www.f2er.com/angularjs/240521.html您可以使用如下所述的TypeScript setter / getter来将fullName与firstName和lastName同步:
get lastName() { return this._lastName; } set lastName(lastName:string) { this._lastName = lastName; this.fullName = this._firstName + ' ' + this._lastName; } get firstName() { return this._firstName; } set firstName(firstName:string) { this._firstName = firstName; this.fullName = this._firstName + ' ' + this._lastName; }
这样设置lastName或firstName时,fullName会自动更新:
var p = new Person(); p.lastName = 'last'; p.firstName = 'first'; console.log(p.fullName); // print 'first last'
第二种方法
默认情况下,Angular2不允许定义对象内属性的更改.它仅检测引用的更新.我的意思是如果更新绑定属性的引用(或基本类型的值).
那个说法,Angular2允许使用ngDoCheck钩子方法插入你自己的策略.
在其中,您可以利用KeyValueDiffers类(要注入)来检测特定对象中的更新.
有关详细信息,请参阅此链接:
> https://angular.io/docs/ts/latest/api/core/DoCheck-interface.html
这是一个示例:
@Component({ selector: 'my-component',(...) }) export class MyComponent implements DoCheck { @Input() person: Person; differ: any; constructor(differs: KeyValueDiffers) { this.differ = differs.find([]).create(null); } ngDoCheck() { var changes = this.differ.diff(this.person); if (changes) { changes.forEachChangedItem((elt) => { if (elt.key === 'firstName' || elt.key === 'lastName' ) { this.person.fullName = this.person.firstName + ' ' + this.person.lastName; } }); } } }
更新prop1属性的值时,将调用doSomethingIfProp1Change方法.
见plunkr:http://plnkr.co/edit/uvOKMXQa9Ik8EiIhb60Y?p=preview.