'calling method from Angular2 template results in NG0100: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked
I would like to call a method from the template, but the call results in NG0100.
How shall I do this properly in Angular2 ?
This is the ts file:
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();
}
}
This is the template:
<p>Here is a random number: {{ getRandom() }}</p>
This is the minimal demo:
https://stackblitz.com/edit/angular-ivy-yuaqfr?file=src/app/app.component.html
Solution 1:[1]
You can use Pipes in Angular, for example:
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());
}
}
And in the html:
<p> {{ 'Here is a random number: ' | random }}</p>
You should declare Pipe same as component.
declarations: [
.
.
RandomPipe
],
Solution 2:[2]
Angular runs change detection by default whenever something change, if you change the value after Angular hasn't finished running the detection, you will get this error, I think you only see this message in dev environment, not on production.
You can solve this by following these 2 approaches in my opinion:
Changing the detection strategy OnPush, there is a good article about this 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();
}
}
Or using the lifecycle hook ngOnInit for assigning a value to random
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>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mahdi Rezazadeh |
| Solution 2 | Andres2142 |
