Issue
In some instances of an AJAX request I am getting a string as a response instead of a number. This causes my Angular2 pipe to break.
{{stat | number:'2.1-2'}}
Is there a way to disable or change the pipe if a string is present?
Solution
I think you will need an additional function for this.
See this plunker for a demo: https://plnkr.co/edit/7eVp2Z99Z47PBWp3eNW4?p=preview
import {Component, NgModule, Pipe, PipeTransform } from '@angular/core'
import {DecimalPipe} from '@angular/common';
import {BrowserModule} from '@angular/platform-browser'
@Pipe({ name: 'myNumber' })
export class MyNumberPipe implements PipeTransform {
transform (value: any, args: string) {
let pipe = new DecimalPipe();
value = isNaN(value) ? 0 : +value;
return pipe.transform(value, args);
}
}
@Component({
selector: 'my-app',
template: `
<div>
<h2>Hello {{name}}</h2>
{{getNumber('3') | number:'2.1-2'}}
<br />
{{getNumber(12) | number:'2.1-2'}}
<br />
{{getNumber('NaN') | number:'2.1-2'}}
<br />
<br />
{{'3' | myNumber:'2.1-2'}}
<br />
{{12 | myNumber:'2.1-2'}}
<br />
{{'NaN' | myNumber:'2.1-2'}}
<br />
</div>
`,
})
export class App {
constructor() {
this.name = 'Angular2'
}
getNumber(val: any) {
if (isNaN(val)) return 0;
return +val;
}
}
@NgModule({
imports: [ BrowserModule ],
declarations: [ App, MyNumberPipe ],
bootstrap: [ App ]
})
export class AppModule {}
Or create your own Pipe
..
Answered By - slaesh
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.