calling method from Angular2 template results in NG0100: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked

calling method from Angular2 template results in NG0100: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked

我想从模板中调用方法,但调用结果为 NG0100。

我该如何在 Angular2 中正确执行此操作?

这是 ts 文件:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {

    public getRandom(): number {
        return Math.random();
    }
}

这是模板:

<p>Here is a random number: {{ getRandom() }}</p>

这是最小的演示:

https://stackblitz.com/edit/angular-ivy-yuaqfr?file=src/app/app.component.html

您可以在 Angular 中使用管道,例如:

import { Pipe, PipeTransform } from '@angular/core';
import * as moment from 'moment';

@Pipe({
  name: 'random'
})

export class RandomPipe implements PipeTransform {
  transform(value: any, ...args: any[]): any {
     return (value + Math.random());
  }
}

并且在 html 中:

<p> {{ 'Here is a random number: ' | random }}</p>

您应该将管道声明为与组件相同。

declarations: [
.
.
RandomPipe
],

Angular 每当发生变化时默认运行变化检测,如果你在 Angular 还没有完成 运行 检测之后更改值,你会得到这个错误,我想您只能在 dev 环境中看到此消息,而不是在 production.

我认为您可以通过以下两种方法解决此问题:

更改检测策略OnPush,有一篇关于此的好文章here

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class AppComponent {
  getRandom(): number {
    return Math.random();
  }
}

或使用生命周期挂钩 ngOnInitrandom

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  random: number = 0;

  ngOnInit() {
    this.random = Math.random();
  }

  getRandom(): void {
    this.random = Math.random();
  }
}

HTML

<p>Here is a random number: {{ random }}</p>
<button (click)="getRandom()">Random</button>