【问题标题】:angular 5: app component redraw several times角度5:应用程序组件重绘几次
【发布时间】:2019-03-17 20:06:39
【问题描述】:

我的 app.component.html:

{{bla()}}

我的 app.component.ts:

import {Component, OnInit, AfterViewInit} from '@angular/core';

@Component({
    selector: 'idr-app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss']
})
export class AppComponent implements AfterViewInit {
    constructor() {}
    ngAfterViewInit() {}

    bla(){
        console.log(77777);
    }
}

我的 app.module.ts:

import {BrowserModule} from '@angular/platform-browser';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';

@NgModule({
    declarations: [
        AppComponent,
    ],
    imports: [
      BrowserModule,


     BrowserAnimationsModule,
    ],
    providers: [

    ],
    bootstrap: [AppComponent],
})
export class AppModule {
}

在控制台我看到这种情况:

app.component.ts:13 77777
app.component.ts:13 77777
core.js:3688 Angular is running in the development mode. Call enableProdMode() to enable the production mode.
app.component.ts:13 77777
app.component.ts:13 77777

如果我在子组件中使用类似 {{bla()}} 的东西,77777 会显示更多次

那么有人知道为什么它会重绘几次吗?

【问题讨论】:

标签: angular angular5 angular2-template redraw


【解决方案1】:

这是由于 Angular 的默认变更检测策略。如果将策略更改为 onPush,您将看到该函数仅执行一次。

这是一个 StackBlitz 示例:https://stackblitz.com/edit/angular-dfhfs7?file=src%2Fapp%2Fapp.component.ts

如果您注释掉更改检测,或将其设置为默认值,您将多次看到控制台语句。如果将其设置为 onPush,则只会看到一次日志语句。

这里有一篇文章可能会有所帮助:https://netbasal.com/a-comprehensive-guide-to-angular-onpush-change-detection-strategy-5bac493074a4

【讨论】:

  • 那么,保留默认更改检测策略会成为问题吗?因为,我看到了一些日志,在控制台中出现了大约 50 次。这实际上意味着该语句被执行了大约 50 次,不是吗?这不会影响性能吗?
  • @RomeoSierra 可以,这取决于存在的组件数量和其他因素。我通常总是禁用默认更改检测。
  • 我明白了。感谢@Brandon 提供的有用信息! :)
猜你喜欢
  • 2023-03-16
  • 1970-01-01
  • 2021-05-10
  • 1970-01-01
  • 2017-10-19
  • 2020-02-25
  • 2018-01-28
  • 1970-01-01
  • 2018-10-30
相关资源
最近更新 更多