LoginSignup
13
15

More than 5 years have passed since last update.

AngularでMarkdownをHTMLとして表示するカスタムpipeを作成する

Last updated at Posted at 2017-11-26

AngularでMarkdownをHTMLとして表示するpipeを作成してみます。
markedパーサーは定番っぽいmarkedを使いました。

前提

今回使用した環境は次の通りです。

$ ng -v
...
Angular CLI: 1.5.4
Node: 9.2.0
OS: darwin x64
Angular: 5.0.3
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, router

@angular/cli: 1.5.4
@angular/flex-layout: 2.0.0-beta.10-4905443
@angular-devkit/build-optimizer: 0.0.33
@angular-devkit/core: 0.0.21
@angular-devkit/schematics: 0.0.37
@ngtools/json-schema: 1.1.0
@ngtools/webpack: 1.8.4
@schematics/angular: 0.1.7
typescript: 2.4.2
webpack: 3.8.1

手順

pipeの作成

markdをインストール
(今回使ったバージョンは1.2.0)

$ npm i markd --save

angluar-cliでパイプを作成します。

$ ng generate pipe mdToHtml

前の手順で作成されたmd-to-html.pipe.tsを編集していきます。

md-to-html.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
import * as marked from 'marked'; // markedをインポート

@Pipe({
  name: 'mdToHtml'
})
export class MdToHtmlPipe implements PipeTransform {

  // 追加
  mdToHtml(md: string): any {
    return marked(md);
  }

  transform(value: any): any {
    // pipeに流れてきた文字列をmarkedに渡す
    return this.mdToHtml(value);
  }
}

pipeの実装は上記のみです。

使い方

実際にテンプレートからパイプを使ってみます。
angluar-cliでpipeを作成した場合、デフォルトでapp.module.tsにインポート&declarationsへの定義が終わっているので、使用したいコンポーネントのテンプレートから呼び出すだけです。

<div [innerHTML]="md | mdToHtml"></div>

innerHTMLというプロパティに変換後のHTMLをバインドして表示しています。

簡単なMarkdownエディタみたいなものです。
(左側のテキストエリア入力したMarkdownが右側でHTMLに変換されて表示される)

app.component.html
<div fxLayout="row">
  <div fxFlex="50%">
    <textarea [(ngModel)]="md" cols="30" rows="50" style="width: 100%"></textarea>
  </div>
  <div fxFlex="50%">
    <div [innerHTML]="md | mdToHtml" style="padding: 10px"></div>
  </div>
</div>

app.moduleに、FormsModuleとFlexLayoutModuleをインポートし、
コンポーネントのクラス側では、入力した内容を格納するmdという変数を定義しているだけです。

スクリーンショット 2017-11-26 18.31.35.png

angular-cliではpipeをテンプレートを作成するコマンドも用意されているので、今回のようなライブラリをパイプに組み込む使い方も簡単に行えました。

参考

13
15
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
13
15