在Angular中动态修改DOM

时间:2018-06-27 19:54:13

标签: javascript angular dom

我正在运行Angular第6版-我试图在Angular中执行在普通JavaScript中相当琐碎的功能。

this.value 是从输入元素中搜索的值, places 是具有城市和州属性的数组-目标是突出显示正在显示的文本在结果列表中搜索每个结果。

有没有办法在Angular中执行此操作? -在阅读ElementRef文档的基础上,似乎不建议以这种方式直接修改DOM。

HTML

<ul class="suggestions"></ul>

JavaScript

const suggestions = document.querySelector('.suggestions'); 
const html = places.map(place => {
const regex = new RegExp(this.value, 'gi');
const cityName = place.city.replace(regex, `<span class="hl">${this.value}</span>`);
const stateName = place.state.replace(regex, `<span class="hl">${this.value}</span>`);
return `<li><span class="name">${cityName}, ${stateName}</span></li>`;
}).join('');

suggestions.innerHTML = html;

1 个答案:

答案 0 :(得分:0)

解决方案:

使用ngFor并绑定[innerHTML]

HTML

<ul class="suggestions">
  <li *ngFor="let place of places" [innerHTML]="buildHTML(place)">
</ul>

JS

buildHTML(place) {
  const regex = new RegExp(this.value, 'gi');
  const cityName = place.city.replace(regex, `<span class="hl">${this.value}</span>`);
  const stateName = place.state.replace(regex, `<span class="hl">${this.value}</span>`);
  return `<li><span class="name">${cityName}, ${stateName}</span></li>`;
}