以下是一个使用Angular Material的示例代码,用于在文本框中高亮显示指定的单词:
ng new angular-material-highlighting
cd angular-material-highlighting
ng add @angular/material
import { MatInputModule } from '@angular/material/input';
import { FormsModule } from '@angular/forms';
@NgModule({
imports: [
BrowserModule,
BrowserAnimationsModule,
MatInputModule,
FormsModule
],
...
})
export class AppModule { }
export class AppComponent {
public text: string;
public highlightedText: string;
public highlightText(): void {
if (this.text) {
this.highlightedText = this.text.replace(/(Angular)/gi, '$1');
} else {
this.highlightedText = '';
}
}
}
在上述代码中,我们使用正则表达式将匹配的单词用标签包裹起来,并设置其背景颜色为黄色。
ng serve
现在你可以在浏览器中打开http://localhost:4200,并在文本框中输入文字,Angular单词将以黄色高亮显示。