这边有个需求,需要监控某个@input的变量变化,突然忘记怎么监听变量了,查了下,记录
这边使用angluar/core中的OnChanges接口,然后实现 ngOnChanges方法,只要变量发生了变化,这里面都可以监听到,然后就可以监听你具体想监听的变量了
import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';
@Component({
selector: 'app-your-component',
template: `
<p>{{ person.name }}, {{ person.age }}</p>
`
})
export class YourComponent implements OnChanges {
@Input() person: { name: string, age: number };
ngOnChanges(changes: SimpleChanges): void {
if (changes.person) {
const newPerson = changes.person.currentValue;
// 在这里执行你的逻辑
this.print(newPerson);
}
}
print(person: { name: string, age: number }) {
console.log(`${person.name}, ${person.age}`);
}
}