角度 5:应用组件重绘几次



My app.component.html:

{{bla()}}

My 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);
}
}

My 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的默认变化检测策略。如果将策略更改为 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

最新更新