window 调整大小时或在 angular 6 中失去焦点时如何防止重新渲染
How can I prevent re-render when window resize or lost focus in angular 6
我在 Angular 6.0.8 中有一个组件,它只包含一个 iframe。
page.component.html:
<iframe [src]="url">
page.component.ts:
ngOnInit() {
this.url = this.route.snapshot.data['url];
}
现在,当我调整 window 大小时或在组件外部单击鼠标(失去焦点)时,angular 将重新呈现它(生命周期挂钩显示:DoCheck、AfterContentChecked、AfterViewChecked)
浏览器会再次请求 iframe 中的 url,这不是我应该做的。
如何防止这种行为?
最推荐的方法之一(不是解决这个具体问题,而是解决所有不需要的重新渲染)是在推送时使用更改检测策略(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 .
示例:
@Component({
selector: 'tooltip',
template: `
<h1>{{config.position}}</h1>
{{runChangeDetection}}
`,
changeDetection: ChangeDetectionStrategy.OnPush
})
我在 Angular 6.0.8 中有一个组件,它只包含一个 iframe。
page.component.html:
<iframe [src]="url">
page.component.ts:
ngOnInit() {
this.url = this.route.snapshot.data['url];
}
现在,当我调整 window 大小时或在组件外部单击鼠标(失去焦点)时,angular 将重新呈现它(生命周期挂钩显示:DoCheck、AfterContentChecked、AfterViewChecked)
浏览器会再次请求 iframe 中的 url,这不是我应该做的。
如何防止这种行为?
最推荐的方法之一(不是解决这个具体问题,而是解决所有不需要的重新渲染)是在推送时使用更改检测策略(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 .
示例:
@Component({
selector: 'tooltip',
template: `
<h1>{{config.position}}</h1>
{{runChangeDetection}}
`,
changeDetection: ChangeDetectionStrategy.OnPush
})