【问题标题】:How to highlight searched text in angular6, using pipe?如何使用管道突出显示angular6中的搜索文本?
【发布时间】:2018-09-29 13:54:51
【问题描述】:

我想建立一个有角度的搜索框,它会返回项目数组,并在结果数组中突出显示 searchedTerm。

例如:在 Chrome 中,如果您正在搜索任何文本,它将以浅黄色背景突出显示。与此类似。

我创建了两个管道,一个用于过滤结果,另一个用于突出显示在搜索结果中的术语。 但我收到错误replace is not a function

另外,两个管道可以合并为一个吗?

highlight.pipe.ts

transform(list: any, searchText: string): any[] {
    if (!list) { return []; }
    if (!searchText) { return list; }

    const re = new RegExp(searchText, 'gi');
    const value = list.replace(re, "<span class='yellow'>" + searchText + "</span>" );
    return list;
}

在模板中使用管道

&lt;div class="card" *ngFor="let item of list | search: searchedTerm | highlight: searchedTerm"&gt;

【问题讨论】:

  • 您可以在您尝试执行replace 的位置添加代码吗?或者只是添加管道中的所有代码
  • 我已经给出了stackblitz url,你可以在其中找到完整的代码。并且还在这里添加了代码。
  • 对不起,我错过了。您最好使用directive 而不是pipe。这是一个您可以在 GitHub github.com/arthurvaverko/ngx-highlight 中查看的示例

标签: angular angular6 angular-pipe


【解决方案1】:

1- 在 highlight.pipe.ts 中

transform(list: any, searchText: string): any[] {
console.log('lists', list);
console.log('searchText', searchText);

if (!list) { return []; }
//to remove highlighted tags before any processing
list = list.map(function (item) {
  item.name = item.name ? String(item.name).replace(/<[^>]+>/gm, '') : '';
  return item;
})
if (!searchText) { return list; }

const re = new RegExp(searchText, 'gi');
const value = list
  .map(function (item) {
    //this will match the values and add the highlight tag for it
    item.name = item.name.replace(re, "<span class='yellow'>" + searchText + "</span>");
    return item
  });
return value;

}

2- 将 .yellow 样式移动到 style.css 以匹配注入的 html

3- 在 app.component.html 中

<div class="card" *ngFor="let item of list | search: searchedTerm | highlight: searchedTerm">
 <span [innerHTML]="item.name"></span>
</div>

如果您希望项目消失,那么如果您只想将其突出显示,则使用搜索管道,那么仅突出显示管道就足够了

更新 Stackblitz 的链接:https://stackblitz.com/edit/angular-searchpipe?file=src%2Fapp%2Fapp.component.html

【讨论】:

  • 感谢您的回复。您所做的更改不会被保存。您需要 Fork(左上角按钮,蓝色)我的示例,然后进行更改。只有这样您的更改才会被保存。
【解决方案2】:


通过searchedTerm 迭代过滤的list。 将突出显示的 html 放入 innerHTML

// html
<div class="card" *ngFor="let item of list | search: searchedTerm">
  <span [innerHTML]="item.name | highlight: searchedTerm"></span>
</div>

// HighlightPipe
const re = new RegExp(searchText, 'gi');
return item.replace(re, `<span class='yellow'>${searchText}</span>` );

III

使用已弃用(移至全局样式)deep 作为组件默认具有模拟ViewEncapsulation

// css
::ng-deep .yellow{
  background: yellow;
}

【讨论】:

  • 感谢您的回复。我有指向数组的高亮管道而不是名称。我现在明白了。谢谢
猜你喜欢
  • 1970-01-01
  • 2019-04-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多