Search code examples
angularngforangular-ng-class

ngClass directive to use with ngFor


I have some list elements, which I am rendering using *ngFor directive. However, some part of the list items text should be bold according to the specs. I tried to do this with the [ngClass]="'strong'" when strong is the css class I need to add some portion on the text. When I run the application the result was the whole text become bold. Below is the screenshot for your better understanding. enter image description here

The requirement is to make the dollar part bold only. I am new to the angular development. Any help would be greatly appreciated.

<ul>
      <li *ngFor="let text of income; let i = index" [ngClass]="'strong'">{{text.text}}</li>
    </ul>
income = [
    {text:'Your Annual Income:* $1,316,422'},
    {text:'Your Monthly Income: $109,702'}
  ];

Solution

  • I have modified only the template part which you have given.

    With the consideration of data from backend, and assuming that the text will be like you have given, the solution as follows..

    Using [innerHTML] property you can give the string split up step by step and when you reach the $ part, just give class <b> </b> like,

    You can split the text part by part like, '<b>'+ text.text.split(' ')[3][0] + '</b>' .

    By this way, you can make only the $ as bold and remaining text as it is..

    <ul>
      <li *ngFor="let text of income; let i = index">
        <div [innerHTML]="text.text.split(' ')[3][0] ? text.text.split(' ')[0] + ' ' + text.text.split(' ')[1]+ ' ' + text.text.split(' ')[2] + ' ' + '<strong>'+ text.text.split(' ')[3][0] + '</strong>' + ' ' + text.text.split(' ')[3].substring(1) : text.text"></div>
        </li>
    </ul>
    

    Working Stackblitz