resize div上的angular2变化检测

Mic*_*ger 16 resize angular2-changedetection angular

我使用bootstrap作为我的布局,我需要检查自动计算的带有引导程序的DIV的大小是否已更改,例如width = 25%.

是否有可能对我未在模板中设置的属性进行更改检测,但是由bootstrap设置.(窗口:调整大小)是不够的.

谢谢

Mar*_*cok 25

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

constructor(private _elRef:ElementRef) {}
ngDoCheck() {
   // use ElementRef to examine the div property of interest
Run Code Online (Sandbox Code Playgroud)

如果div它位于组件模板中,请添加本地模板变量

<div #myDiv ...>
Run Code Online (Sandbox Code Playgroud)

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

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

请注意,每次更改检测运行时都会调用ngDoCheck()和ngAfterViewChecked().另请参阅开发指南Lifecycle Hooks.


Dil*_*age 5

我遇到了同样的问题,所以我使用了名为Angular-Resize-Event的轻量级库。

https://www.npmjs.com/package/angular-resize-event

<div (resized)="onResized($event)"></div>
Run Code Online (Sandbox Code Playgroud)

安装后,只需将此输出事件添加到要检查大小更改的任何div中。