首页 > 解决方案 > 根据Angular中的文本突出显示文本

问题描述

customers.json 文件 json 文件

客户服务.ts

服务.ts

userdetails.component.ts

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

userdetails.component.html html 文件

所以请我只想将goodword和badwords数组与句子数据的json文件进行比较,找到句子中的goodwords和badwords,如果是goodword则突出显示该单词,然后以绿色背景突出显示,badword以红色背景突出显示。

标签: angulartypescripthighlightangular7

解决方案


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

Stackblitz 演示 在这里

零件

请记住将goodWordsandbadWords数组中的所有单词都设为小写

 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。希望这对您有用。


推荐阅读