innerHTML 方法的难点之一是<mark>标记样式。另一种方法是将其放置在组件中,从而在样式中提供更多选项。
突出显示的text.component.html
<mark *ngIf="matched">{{matched}}</mark>{{unmatched}}
突出显示的text.component.ts
import { Component, Input, OnChanges, OnInit } from "@angular/core";
@Component({
selector: "highlighted-text",
templateUrl: "./highlighted-text.component.html",
styleUrls: ["./highlighted-text.component.css"]
})
export class HighlightedTextComponent implements OnChanges {
@Input() needle: String;
@Input() haystack: String;
public matched;
public unmatched;
ngOnChanges(changes) {
this.match();
}
match() {
this.matched = undefined;
this.unmatched = this.haystack;
if (this.needle && this.haystack) {
const needle = String(this.needle);
const haystack = String(this.haystack);
const startIndex = haystack.toLowerCase().indexOf(needle.toLowerCase());
if (startIndex !== -1) {
const endLength = needle.length;
this.matched = haystack.substr(startIndex, endLength);
this.unmatched = haystack.substr(needle.length);
}
}
}
}
突出显示的text.component.css
mark {
display: inline;
margin: 0;
padding: 0;
font-weight: 600;
}
用法
<highlighted-text [needle]=searchInput [haystack]=value></highlighted-text>