Angularでハイライト実装


Angularでハイライト機能の実装をしたので記録用として残します。
今回は angular-text-input-highlight を参考に実装。

  開発環境

  • Angular6(Typescript)

 使用したライブラリ

  • angular-text-input-highlight

実装

npmからインストール

$ npm install --save angular-text-input-highlight

アプリのどこかにスタイルシートを含める

angular.json
"styles": [
node_modules/angular-text-input-highlight/text-input-highlight.css
],

moduleに追記する

sample.module.ts
import { NgModule } from '@angular/core';
import { TextInputHighlightModule } from 'angular-text-input-highlight';


@NgModule({
  imports: [
    TextInputHighlightModule
  ]
})
export class SanpleModule {}

htmlの実装

ハイライトの関数を呼び出すために仮でボタンを設置

sample.component.html
 <button class="btn" (click)="addTags()">
   <i aria-hidden="true">ハイライトボタン</i>
 </button>
 <div mwlTextInputHighlightContainer class="form-group" >
   <textarea
    mwlTextInputElement
    rows="4"
    class="form-control"
    [(ngModel)]="sampleText"
    #textarea
    >{{ sampleText }}
  </textarea>
  <mwl-text-input-highlight
   [tags]="tags"
   [tagCssClass]="'bg-blue'"
   [textInputElement]="textarea"
   >
  </mwl-text-input-highlight>
 </div>

cssの実装

sample.component.scss
 .bg-blue {
   background-color: lightblue;
 }

.bg-pink {
  background-color: lightcoral;
}
textarea {
 width: 500px;
}

tsファイルの実装

sample.component.ts
 import { ViewEncapsulation } from '@angular/core';

import { HighlightTag } from 'angular-text-input-highlight';

@Component({
  selector: 'app-sample',
  templateUrl: './sample.component.html',
  styleUrls: ['./sample.component.scss'],
  encapsulation: ViewEncapsulation.None,
})

export class SampleComponent implements {
  sampleText: string = 'Hello @mattlewis92 how are you today?\n\nLook I have a #different background color!';

  tags: HighlightTag[] = [];

  public addTags(): void {
    this.tags = [];

    const matchMentions = /(@\w+) ?/g;
    let mention;
    // tslint:disable-next-line
    while ((mention = matchMentions.exec(this.sampleText))) {
      this.tags.push({
        indices: {
          start: mention.index,
          end: mention.index + 1,
        },
        data: mention[1],
      });
    }

    const matchHashtags = /(#\w+) ?/g;
    let hashtag;
    // tslint:disable-next-line
    while ((hashtag = matchHashtags.exec(this.sampleText))) {
      this.tags.push({
        indices: {
          start: hashtag.index,
          end: hashtag.index + hashtag[1].length,
        },
        cssClass: 'bg-pink',
        data: hashtag[1],
      });
    }

 }

補足

  • matchMentions はハイライトさせたい文字を正規表現で記載する。
  • 下記でthis.sampleTextと記載している部分がハイライトさせたい文章全体。

while ((mention = matchMentions.exec(this.sampleText)))

動作確認

ボタンを押す前 

ボタンを押した後 

 おわりに

他にもAngularでハイライトが可能なライブラリがありましたが、これが一番スムーズに実装できました。