angular2 change detection on resize div

2019-06-15 00:09发布

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.

Is there a possibility to do change detection on a attribute which I don't set in my template, but is set by bootstrap. (window:resize) is not enough.

thx

4条回答
甜甜的少女心
2楼-- · 2019-06-15 00:36

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.

查看更多
你好瞎i
3楼-- · 2019-06-15 00:37

I have tried the correct answer but the refresh rate wasn't very accurate, So I looked for another solution.

Here it is

// 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 ...
}

Then you can use it in any element like:

<app-component resize-detector></app-component>
查看更多
贪生不怕死
4楼-- · 2019-06-15 00:41

There are few methods to track DOM attribute changes:

  • polling i.e. setInterval
  • DOM mutation events: DOMAttrModified + propertychange for IE
  • implementing MutationObserver
查看更多
迷人小祖宗
5楼-- · 2019-06-15 00:42

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.

查看更多
登录 后发表回答