Split and Replace string in Angular 8 HTML

Viewed 5539

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?

  • 2 Answers

    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

    Hey you just have to make custom pipe and use that pipe in your html to format the string as per your requirement.

    To make the custom pipe use the following lines of code:

    @Pipe({ name: 'myPipe' })
    export class MyPipe implements PipeTransform {
    
        transform(value: any) {
            if (value) {
               let firstLine= value.substr(0,9);
               let secondLine= value.substr(9).bold();
               
                return firstLine+'/n'+secondLine
            }
            return value;
        }
    
    }
    
    Related