How to perform change detection on div resizing

Michael Burger picture Michael Burger · Apr 18, 2016 · Viewed 46k times · Source

I use Bootstrap for my layout and I need to check if the automatic calculated size of my div with bootstrap for example width = 25% is changed.

How to perform change detection on a attribute which I don't set in my template, but is set by Bootstrap?

(window:resize) is not enough.

Answer

Mark Rajcok picture Mark Rajcok · Apr 18, 2016

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

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

<div #myDiv ...>

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

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