Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I prevent re-render when window resize or lost focus in angular 6

I have a component in Angular 6.0.8, which only contain an iframe.

page.component.html:

<iframe [src]="url">

page.component.ts:

ngOnInit() {
    this.url = this.route.snapshot.data['url];
}

Now, when I resize the window or click mouse outside of component (lost focus), angular will re-render it (lifecycle-hooks shows: DoCheck, AfterContentChecked, AfterViewChecked)

And browser will request the url in the iframe again, which is not what i supposed to.

How to prevent this behavior?

like image 553
Raven Avatar asked Nov 16 '18 08:11

Raven


1 Answers

One of the most recomended ways (to solve not this concrete problem, but all unneeded rerenders) is to use change detection strategy on push (ChangeDetectionStrategy.OnPush).

A comprehensive guide to angular onpush change detection strategy

By default Angular uses the ChangeDetectionStrategy.Default change detection strategy.

The default strategy doesn’t assume anything about the application, therefore every time something changes in our application, as a result of various user events, timers, XHR, promises, etc., a change detection will run on all components.

This means anything from a click event to data received from an ajax call causes the change detection to be triggered.

...

OnPush Change Detection Strategy

We can set the ChangeDetectionStrategy of our component to ChangeDetectionStrategy.OnPush .

Example:

@Component({
  selector: 'tooltip',
  template: `
   <h1>{{config.position}}</h1>
    {{runChangeDetection}}
  `,
  changeDetection: ChangeDetectionStrategy.OnPush
})
like image 54
Eugene Mihaylin Avatar answered Oct 27 '22 00:10

Eugene Mihaylin