[英]change detection angular 2 model's property
I need to call a JQuery function each time if my model's propery got changed. 如果模型的属性发生更改,则每次都需要调用JQuery函数。
person = {firstName:firstName, lastName:lastName}
as an example If I changed the firstName property of person object, every time I need to trigger a function. 例如,如果我更改了人员对象的firstName属性,则每次需要触发一个函数时。 Actually I need a something like subscription to this object's property. 实际上,我需要类似订阅此对象属性的内容。
How is it possible? 这怎么可能?
thanks in advance. 提前致谢。
It sounds like you are looking for the DoCheck
( link to docs ) life cycle hook. 听起来您正在寻找DoCheck
( 指向文档的链接 )生命周期挂钩。 It is an event that will be triggered after every completed round of change detection. 此事件将在每轮完整的变更检测之后触发。 Keep in mind though that it will potentially be triggered a lot, and doing heavy operations in that hook could have a major negative impact on performance. 请记住,尽管它可能会被触发很多,并且在该挂钩中执行繁重的操作可能会对性能产生重大负面影响。
Here is an example that looks for changes on the person.firstName
property, and logs it to the console if changes are found: 这是一个示例,该示例在person.firstName
属性上查找更改,如果找到更改,则将其记录到控制台:
import { Component, DoCheck } from '@angular/core';
@Component({
selector: 'app-root',
template: `<input type="text" [(ngModel)]="person.firstName">`,
styleUrls: ['./app.component.css']
})
export class AppComponent implements DoCheck {
person = { firstName: 'Donald', lastName: 'Duck' };
oldFirstName: string;
ngDoCheck() {
if (this.person.firstName !== this.oldFirstName) {
console.log(`Change first name from "${this.oldFirstName}" to "${this.person.firstName}"`);
this.oldFirstName = this.person.firstName;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.