Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?
  • like image 210
    Bitly Avatar asked Nov 15 '25 10:11

    Bitly


    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

    like image 164
    Sivakumar Tadisetti Avatar answered Nov 17 '25 07:11

    Sivakumar Tadisetti


    For a simple use case it might not be necessary to add a pipe.

    I've done the following

    In .ts

    myName;
    
    // data received
    handleData(data) {
      var originalName = data.name;
      this.myName = originalName.split("name")[0]
    }
    

    In the .html

    {{myName}}
    
    like image 36
    Marian07 Avatar answered Nov 17 '25 07:11

    Marian07



    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!