【问题标题】:Highlight the text according to text in Angular根据Angular中的文本突出显示文本
【发布时间】:2019-08-13 11:24:18
【问题描述】:

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

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

【问题讨论】:

  • 请添加到目前为止您尝试过的代码示例。
  • 请不要将代码作为链接发布,分享您迄今为止尝试过的任何内容并尽可能重现问题(使用 stackblitz 进行角度分析)。
  • 我只是在尝试这种方法: for (var i = 0; i " + this.goodwords[i] + "") }
  • @Tushar 是一位新的贡献者。建议他如何提问。 Stack Overflow 不仅适用于 SMART 人。我们应该欢迎这里的每一位新手。因此,通过建议他来帮助他,而不是通过负面反馈让他失去动力。

标签: angular typescript highlight angular7


【解决方案1】:

对于这个问题,我没有那么多负面反馈,而是在这里给你一个答案。

Stackblitz Demo 这里

组件

请记住将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 本身的所有事情。希望这对您有用。

【讨论】:

  • 您能否就 indexof 行提供帮助,它为我提供了相应的输出,但它在控制台上给出错误,即无法读取 Object.eval [as updateDirectives] 处未定义的属性“indexOf”,这会影响我的洞 app.so你能建议我不要在 html 文件中写 indexof 行吗?我们可以在 ts 文件中写那行吗?如果你有解决方案,请提供给我,谢谢
  • 我已经更新了我的答案。请参见。我已经改变了两个 *ngIf 条件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-11
  • 1970-01-01
  • 1970-01-01
  • 2018-06-01
  • 2020-04-06
相关资源
最近更新 更多