根据 Angular 中的文本突出显示文本

Highlight the text according to text in Angular

customers.json 文件 json file

customer.service.ts

service.ts

userdetails.component.ts

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

userdetails.component.html html file

所以我只想将好词和坏词数组与句子数据的 json 文件进行比较,找到句子中的好词和坏词,并突出显示该词,如果它是好词,则突出显示绿色背景和红色背景的坏词。

与其对这个问题有那么多负面反馈,我来给你一个答案。

Stackblitz Demo 此处

Component

记得将 goodWordsbadWords 数组中的所有单词设为小写

 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>

所以我已经处理了 HTML 本身的所有事情。希望这对您有用。