【发布时间】:2022-08-02 19:13:33
【问题描述】:
我需要听取被<ng-content> 替换的元素的类名更改。我尝试了很多方法,我发现的唯一方法是使用setInterval,我认为这不是一个好习惯。假设我将在<app-child> 组件内注入一个input 元素
@Component({
selector: \'app-parent\',
template: `
<app-child>
<input type=\"text\">
</app-child>
`
})
export class ParentComponent implements OnInit {
ngOnInit() { }
}
并且每当input 的class 属性发生变化时,我都想在child.component.ts 内部做一些事情:
@Component({
selector: \'app-child\',
template: `<ng-content select=\"input\"></ng-content>`
})
export class ChildComponent implements OnInit {
@ContentChild(HTMLInputElement) input: any;
ngOnInit() {
setInterval(() => {
const { className } = this.input.nativeElement;
console.log(className);
}, 500);
}
}
这种方法设法检测到类更改,但setInterval 的问题是该回调将每隔500 毫秒在后台运行一次,是否有另一种方法来检测更改?
注意:我已经尝试过钩子ngAfterContentChecked,它会在检测到任何更改后自动运行,但在内部我无法访问this.input.nativeElement.className 上的最新更改,就好像该函数在值更改之前执行一样。
标签: angular angular-changedetection angular-lifecycle-hooks