Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform change detection on div resizing

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.

like image 310
Michael Burger Avatar asked Apr 18 '16 13:04

Michael Burger


People also ask

How to detect div resize?

In the mean time, you can use function like the following. Since, the majority of element size changes will come from the window resizing or from changing something in the DOM. You can listen to window resizing with the window's resize event and you can listen to DOM changes using MutationObserver .

How do I stop a DIV from resizing?

It is mostly used with textarea and div elements. To disable resizable property of an element use resize to none.

How do I resize a content to fit in a div?

Answer: Use the CSS max-width Property You can simply use the CSS max-width property to auto-resize a large image so that it can fit into a smaller width <div> container while maintaining its aspect ratio.


2 Answers

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.

like image 158
Mark Rajcok Avatar answered Oct 17 '22 22:10

Mark Rajcok


I had the same problem so I used the lightweight library called Angular-Resize-Event

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

<div (resized)="onResized($event)"></div>

After installing it just add this output event to any div which you want to check for size changes.

like image 11
Dilshan Liyanage Avatar answered Oct 18 '22 00:10

Dilshan Liyanage