且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在div调整大小上执行更改检测

更新时间:2021-09-26 09:40:26

您可以向 div 添加指令,并实现生命周期挂钩 ngDoCheck()来执行自己的操作更改检测逻辑.您需要注入 ElementRef :

You can add a directive to the div and implement lifecycle hook ngDoCheck() to perform your own change detection logic. You'll need to inject ElementRef:

constructor(private _elRef:ElementRef) {}
ngDoCheck() {
   // use ElementRef to examine the div property of interest

如果 div 在组件模板内部,请添加本地模板变量

If the div is inside a component template, add a local template variable

<div #myDiv ...>

然后使用 @ViewChild()获取对 div 的引用,并实现生命周期挂钩 ngDoCheck() ngAfterViewChecked()来执行您自己的变更检测逻辑.

Then use @ViewChild() to get a reference to the div and implement lifecycle hook ngDoCheck() or ngAfterViewChecked() to perform your own change detection logic.

@ViewChild('myDiv') theDiv:ElementRef;
ngAfterViewChecked() {
   // use this.theDiv to examine the div property of interest

请注意,每次运行更改检测时,都会调用ngDoCheck()和ngAfterViewChecked().另请参阅开发指南生命周期挂钩.

Note that ngDoCheck() and ngAfterViewChecked() will be called every time change detection runs. See also the dev guide Lifecycle Hooks.