我使用bootstrap作为我的布局,我需要检查自动计算的带有引导程序的DIV的大小是否已更改,例如width = 25%。
是否有可能对我未在模板中设置的属性进行更改检测,但是由bootstrap设置。 (窗口:调整大小)是不够的。
谢谢
您可以向div
添加指令并实现生命周期钩ngDoCheck()
以执行您自己的更改检测逻辑。你需要注入ElementRef
:
constructor(private _elRef:ElementRef) {}
ngDoCheck() {
// use ElementRef to examine the div property of interest
如果div
位于组件模板中,请添加本地模板变量
<div #myDiv ...>
然后使用@ViewChild()
获取对div
的引用,并实现生命周期钩ngDoCheck()
或ngAfterViewChecked()
来执行您自己的更改检测逻辑。
@ViewChild('myDiv') theDiv:ElementRef;
ngAfterViewChecked() {
// use this.theDiv to examine the div property of interest
请注意,每次更改检测运行时都会调用ngDoCheck()和ngAfterViewChecked()。另见开发指南Lifecycle Hooks。
我遇到了同样的问题所以我使用了名为Angular-Resize-Event的轻量级库
https://www.npmjs.com/package/angular-resize-event
<div (resized)="onResized($event)"></div>
安装后,只需将此输出事件添加到要检查大小更改的任何div。
我已经尝试了正确的答案,但刷新率不是很准确,所以我寻找另一种解决方案。
这里是
// Directive
@Directive({
selector: '[resize-detector]',
})
public constructor(public element: ElementRef<HTMLElement>) {}
public ngOnInit(): void {
// Call detectResize as whe the element inits the windows resize event most likely won't trigger
this.detectResize();
}
// if you need the windowDimensions add ", [$event]" to @HostListener and pass event to detectResize(event)
@HostListener('window:resize')
public detectResize(): void {
console.log(element.nativeElement.offsetWidth);
console.log(element.nativeElement.offsetHeight);
// Do you magic here ...
}
然后你可以在任何元素中使用它,如:
<app-component resize-detector></app-component>
跟踪DOM属性更改的方法很少:
setInterval
DOMAttrModified
+ propertychange
MutationObserver