Home > Mobile >  How can I make my formatting conditional with pipes in angular html
How can I make my formatting conditional with pipes in angular html

Time:12-31

How can I do some conditional formatting. The code below formats it to two decimal places. However sometimes the row[column.props] comes out as not of type number. Sometimes it has a value of text like 'n/a' how can I do conditional formatting in this case? I don't want to format it as number if it is not a number.

<td *ngFor = "let column of headers">
  {{row[column.prop] | number: '1.1-2'}}
</td>

CodePudding user response:

You can use *ngIf in your template to see if the value is a number. If the value is not a number use else to render a different template.

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  public values: any[] = [1.23, 11.134223, 'n/a', 0, 'n/a'];
}
<ng-container *ngFor="let val of values">
  <div *ngIf=" val; else nonNumberTemplate">{{ val | number: '1.1-2' }}</div>
  <ng-template #nonNumberTemplate>
    <div>{{ val }}</div>
  </ng-template>
</ng-container>

https://stackblitz.com/edit/angular-ivy-5gmgnu

  • Related