Search code examples
htmlangulartypescriptangular8

Split and Replace string in Angular 8 HTML


I am receiving data from REST api. For name parameter, I want to split it at 2330 and give new line break. Example: I have name: ABCD 2330 This is My Name I want to give different style to the split strings and the output on my screen to be:

ABCD 2330
This is My Name // this will be bold

and not

ABCD 2330 This is My Name

Given the complexity of my object, I don't think I can put this operation in the ts file. I am binding the data like: <li>{{data.name}}</li> can I use some pipe like split and how would I add /n after the split and rejoin the string and also how can I give different style in the same

  • tag?


  • Solution

  • Maybe you can try like below

    Pipe

    import { Pipe, PipeTransform } from '@angular/core';
    
    @Pipe({name: 'texttransform'})
    export class TextTransformPipe implements PipeTransform {
      transform(value: string): string {
        const splitBy = '2330'
        const splittedText = value.split( splitBy );
        return `${ splittedText[0] } ${ splitBy } <br> <b>${ splittedText[1] }</b>`;
      }
    }
    

    And in the template file

    <ul>
      <li *ngFor="let data of receivedData" [innerHTML]="data.name | texttransform"></li>
    </ul>
    

    Working stackblitz