LoginSignup
4
4

More than 5 years have passed since last update.

取得したHTMLタグ入りの文字列をAngualr, Ionic上で表示 styleタグもいける

Posted at

IonicでHTMLタグの入った、特にStyleタグの入ったコンテンツを表示する必要がありました。
内容的には基本的すぎることなんですが、Componentの中でSanitizer使って作っても、型エラーで反映できなかったので共有のためシェアしておこうかなと。

結論から言うとこういうPipe作った。

safe-html.ts
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Pipe({
  name: 'safeHTML',
})
export class SafeHtmlPipe implements PipeTransform {

  constructor(private sanitizer: DomSanitizer) {}

  transform(value) {
    return this.sanitizer.bypassSecurityTrustHtml(value);
  }
}

これをView側で呼び出す。Componentのメソッドの中でやろうとしても何故か上手くいかなかったので、おとなしくパイプを作りました。

<div [innerHTML]="contents | safeHTML"></div>

あとはComponentの方で、contentsに対してHTMLタグ、それもStyleタグ入りの文字列をバインドしてあげてください。

4
4
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
4
4