LoginSignup
3
3

More than 5 years have passed since last update.

Angularでテキスト検索のハイライト表示

Posted at

Angularでテキストを表示しているエレメントに対して文字列検索を行い、一致する文字列部分をハイライト表示する。

HTMLテンプレート側

検索文字列はinput要素と双方向バインドしておくと、文字列の入力にあわせてリアルタイムに反応してくれる。

sample.html
<!-- 検索文字列を入力するinput要素 -->
<input id="key" type="text" [(ngModel)]="key">
<!-- 文字列を表示するdiv要素 -->
<div [innerHTML]=emphasis()></div>

データ側

テキストのうち、キーワードに該当する部分のスタイルを"赤文字"かつ"太文字"でハイライト表示にする。
AngularでinnerHTMLを埋め込もうとするとサニタイズされてしまうので、DomSanitizerでSafeHtmlにしてから値を返すようにする。

sample.ts

import { DomSanitizer, SafeHtml } from '@angular/platform-browser';

private target: string; //テキスト表示している文字列
private key: string; //検索キーワード

constructor(
  private sanitizer: DomSanitizer
) {}

private emphasis(): SafeHtml {
  const regexp = new RegExp(this.key , 'g');
  if (this.key !== '') {
    return this.sanitizer.bypassSecurityTrustHtml(
      target.replace(regexp, '<span style="color: #FF0000;font-weight: bold;">' + this.key + '</span>'));
  } else {
    return target;
  }
}

検索文字列を打ち込んでいくと、テキストの該当する部分が赤い太文字として強調される。

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3