使用Angular实现高亮功能

因为使用Angular实现了高亮功能,所以将其记录下来作为备忘。
这次是参考了angular-text-input-highlight来实现。

开发环境

    Angular6(Typescript)

使用的库

    angular-text-input-highlight

实施

从npm上安装

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

将样式表包含在应用的某个地方

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

在该模块中进行追加记录

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


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

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 的实现

 .bg-blue {
   background-color: lightblue;
 }

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

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と記載している部分がハイライトさせたい文章全体。

当(mention = matchMentions.exec(this.sampleText))时

确认行动

image.png

最后

还有其他能够在Angular中实现高亮功能的库,但这个库能够最顺利地实现。

bannerAds