我试图在 {{receipt}} 输出中突出显示提交到输入中的搜索查询。
组件.html:
<h5 style="text-decoration: underline">Your Receipt</h5>
<pre>
{{receipt}}
</pre>
Product Search:<input type="text" (input)="onSearchChange($event.target.value)">
<br>
<span>Total Price: {{total}}</span>
</div>
组件.ts:
onSearchChange(SearchValue){
if((this.receipt).includes(SearchValue)){
};
如您所见,到目前为止我唯一设法完成的事情是检查提交的输入是否存在于收据变量中。我想以某种方式强调它。
如有任何建议,我们将不胜感激。谢谢
编辑:我在看: https://stackblitz.com/edit/angular-highlight-directive
但我不确定如何在我的案例中实现该指令
最佳答案
如果没有指令,您可以使用以下代码实现相同的功能
在你的 TS 文件中
import { Renderer2} from '@angular/core';
@ViewChild('refEl', { static:true }) refEl;
constructor(private renderer: Renderer2) { }
receipt = "hello"
onSearchChange(value){
if((this.receipt).includes(value)){
this.renderer.setProperty(
this.refEl.nativeElement,
'innerHTML',
this.getFormattedText(value)
);
};
}
getFormattedText(value){
const valuestring = value.trim().split(' ')
const re = new RegExp(`(${ valuestring.join('|') })`, 'g');
return this.receipt.replace(re, `<span class="selected">$1</span>`);
}
在您的 html 中
<div>
<h5 style="text-decoration: underline">Your Receipt</h5>
<pre #refEl> {{receipt}} </pre>
Product Search:<input type="text" (input)="onSearchChange($event.target.value)">
<br>
<span>Total Price: {{total}}</span>
</div>
在您的 .css 文件中
::ng-deep .selected {
color:red;
}
编辑:我整理了一个stackblitz以防万一
关于angular - 是否可以以 Angular 突出显示文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59612037/