Search code examples
angulartypescripthighlightangular7

Highlight the text according to text in Angular


customers.json file json file

customer.service.ts

service.ts

userdetails.component.ts

userdeatils.component.ts 1 userdetails.component.ts 2

userdetails.component.html html file

so please I just Want to compare the goodword and badwords array with the json file of sentence data and find the goodwords and badwords in the sentence and highlight the word according if it is goodword then it highlight with green background and badword with red background.


Solution

  • Instead of so much negative feedback on this question, I am here to give you an answer.

    Stackblitz Demo here

    Component

    Remember to make all the words in lowercase in the goodWords and the badWords array

     obj = {
        customer: [
          {
            threshold: 80,
            sentence: 'Agent : Thank you for calling ABC company. My name is Ashley. How may I help you today?'
          },
          {
            threshold: 40,
            sentence: 'Customer : I am calling because I recieved a wrong bill. I just paid my phone bill two days ago.'
          },
        ]
      };
      goodWords = ['thank', 'you', 'help', 'sorry', 'please'];
      badWords = ['wrong', 'our', 'last', 'my'];
    

    HTML

    <div *ngFor="let item of obj.customer">
        <span *ngFor="let word of item.sentence.split(' ')">
    
        <span *ngIf="goodWords && goodWords.indexOf(word.trim().toLowerCase()) > -1; else redWord">
          &nbsp;<span style="color: green">{{word}}</span>
        </span>
    
        <ng-template #redWord>      
          <span *ngIf="badWords && badWords.indexOf(word.trim().toLowerCase()) > -1; else other" style="color: red">
            {{word}}
          </span>
        </ng-template>
    
        <ng-template #other>
          {{word}}
        </ng-template>
      </span>
       <br><br>
    </div>
    

    So I have handled all the things in the HTML itself. Hopefully, this will work for you.