LoginSignup
12
8

More than 5 years have passed since last update.

Angular > テンプレート内で、テンプレートを参照する。(ng-containerでng-templateを参照)

Last updated at Posted at 2018-06-22

わざわざ新しいコンポーネントを定義するほどではないけど、同じテンプレートの中で一定の記述を使い回したい時があります。
うまく記事が見つけられなかったので一応メモ。

こちらが参考になります

<!-- 使いまわしたい記述を ng-template で宣言 -->
<ng-template #template let-text="text">
 <p> {{ text }} </p>
</ng-template>

<!-- テンプレートを ng-container から利用する -->
<ng-container *ngTemplateOutlet="template; context:{ text: 'hoge' }"></ng-container>
<ng-container *ngTemplateOutlet="template; context:{ text: 'huga' }"></ng-container>

こちらを実行すると以下のDOMが生成されます。

<p> hoge </p>
<p> huga </p>

ng-contenerでは *ngTemplateOutlet によって、テンプレートと、context を指定します。
context はテンプレートで使用する変数になります。

ng-templateは context から受け取る変数を let-{context内のプロパティ}={変数名} で宣言し、
内部で利用できます。

12
8
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
12
8