2017.5.27
2017.6.1

タグや特殊文字(< >など)をHTMLとして出力する方法

AngularJSがそうだったようにAngularでもセキュリティの観点からか、modelに設定されたHTMLや特殊文字(< >など)は、デフォルトでは単なる文字列としてそのまま出力されます。

AngularJSでは「ngSanitize」モジュールを使って「ng-bind-html」でHTMLとして出力が可能でしたが、Angularでは記述の仕方が変わっているようなので、以下はその方法になります。

目次

  • ディレクトリ、ファイルの構成
  • HTML出力部
  • モジュール部
  • コンポーネント部
  • 実際の表示
  • 参考リンク

ディレクトリ、ファイルの構成

今回、試してみたディレクトリ、ファイルの構成は以下の通りです。(HTML出力用に作成またはコードを追加したファイルのみ表示)

project
├ node_modules
└ src
    └ app
        ├ app.module.ts
        ├ app.html-safe.pipe.ts
        └ example
            ├ example.component.html
            └ example.component.ts

HTML出力部

app.html-safe.pipe.ts


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

@Pipe({ name: 'htmlSafe' })
export class HtmlSafePipe implements PipeTransform {
  constructor(private sanitizer: DomSanitizer) { }
  transform(str: string): SafeHtml {
    return this.sanitizer.bypassSecurityTrustHtml(str);
  }
}

HTMLとして出力したい文字列を「bypassSecurityTrustHtml」メソッドで変換しています。

モジュール部

app.module.ts


import { NgModule }      from '@angular/core';
import { HtmlSafePipe } from './app.html-safe.pipe';

@NgModule({
  declarations: [
    HtmlSafePipe,
  ],
})

モジュールに「HtmlSafePipe」クラスを登録したら、後は利用したい箇所で呼び出すだけです。

コンポーネント部

example.component.html


<span [innerHtml]="title | htmlSafe"></span>

AngularJSで「ng-bind-html」で記述していた箇所が、[innerHtml]に変わっています。

example.component.ts


import { Component } from '@angular/core';

@Component({
  templateUrl: 'example.component.html'
})
export class ExampleComponent {
  title = "HTML<br/>出力&amp;&lt;&gt;";
}

実際の表示

上記のtitle文字列「HTML<br/>出力&amp;&lt;&gt;」が、ブラウザ上では以下のように表示されます。

HTML
出力&<>

参考リンク

Angular】関連記事