在Angular中,可以使用ngOnChanges
生命周期钩子来监听返回某个变量的变化。下面是一个包含代码示例的解决方法:
myVariable
:import { Component, OnChanges, SimpleChanges } from '@angular/core';
@Component({
selector: 'app-my-component',
template: `
My Component
`
})
export class MyComponent implements OnChanges {
myVariable: any;
ngOnChanges(changes: SimpleChanges) {
if (changes.myVariable) {
console.log('myVariable has changed:', this.myVariable);
// 在这里处理变量变化的逻辑
}
}
}
myVariable
:
myVariable
的值发生变化时,ngOnChanges
方法将会被调用。你可以在这个方法中处理变量变化的逻辑。请注意,ngOnChanges
方法只有在输入属性发生变化时才会被触发。如果你需要监听一个本地变量的变化,可以考虑使用ngDoCheck
生命周期钩子。