gpt4 book ai didi

javascript - 当窗口调整大小时或在 Angular 6 中失去焦点时如何防止重新渲染

转载 作者:太空狗 更新时间:2023-10-29 17:53:14 26 4
gpt4 key购买 nike

我在 Angular 6.0.8 中有一个组件,它只包含一个 iframe。

page.component.html:

<iframe [src]="url">

页面.component.ts:

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

现在,当我调整窗口大小时或在组件外部单击鼠标(失去焦点)时,angular 将重新渲染它(生命周期 Hook 显示: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
})

关于javascript - 当窗口调整大小时或在 Angular 6 中失去焦点时如何防止重新渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53334389/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com