Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid argument 'NaN' for pipe 'DecimalPipe'

Tags:

angular

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?

like image 878
cport1 Avatar asked Oct 12 '25 21:10

cport1


1 Answers

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..

like image 114
slaesh Avatar answered Oct 14 '25 16:10

slaesh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!