Issue
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
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
],
Answered By - Mahdi Rezazadeh
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.