Search code examples
angularionic-frameworkpipeangular-ng-if

Check if a string starts with certain character using ngIf and display it


I am newbies here and I have problem to solve. Please do help, thanks in advance.

I usually display data on screen like this and it works everytime.

<h3> Kod Bar : {{ article.barcode_no }} </h3>

But now I want to check using *ngIf if article.barcode_no starts with certain character, I want it to be remove first before displaying it like this.

<h3 *ngIf=" article.article.indexOf(article.barcode_no) === 'S' ? (article.barcode_no).substr(1) : none "> Kod Bar    : {{ article.barcode_no }} </h3>

But I keep getting error

ERROR TypeError: Cannot read property 'indexOf' of undefined

I also tried using Pipe but not working. Please help. Thank you.

 <h3 *ngIf=" (article.barcode_no | startsWith : 'S') ? (article.barcode_no).substr(1) : none "> Kod Bar    : {{ article.barcode_no }} </h3>

.

import { Pipe, PipeTransform, Injectable } from '@angular/core';

@Pipe({
    name: 'startsWith'
})

export class AccessProviders implements PipeTransform {

  transform(fullText: string, textMatch: string) : boolean {
      return fullText.startsWith(textMatch);
  }
}

[ THANK YOU FOR REPLYING YOU GUYS. I APPRECIATE ALL THE ANSWERS! ]


Solution

  • You can try this.

    <h3 *ngIf="article.barcode_no.indexOf('S',0) == 0 "> Kod Bar    : {{ article.barcode_no.substring(1) }} </h3>
    

    Stackblitz demo