LoginSignup
26
24

More than 5 years have passed since last update.

ng-contentを使ってみる

Posted at

ng-contentとは

componentの中に外から要素を注入したいときに使います。angular1でいうところのngTranscludeに近いですね。

とりあえず子要素を注入してみる

とりあえず子要素を突っ込むには、突っ込みたい位置に<ng-content></ng-content>を置きます。それだけです。

@Component({
  selector: 'foo',
  template: `
    <ng-content></ng-content>
  `,
})
export class Foo {

}
<foo>
  <div>hello</div>
</foo>

複数の要素を入れたいところに入れる

あれはここ、それはこっちに配置したいみたいなのをやりたければ<ng-content select="...">を使います(DEMO)。

@Component({
  selector: 'bar',
  template: `
    <section>
      <h3>tag selector(foo)</h3>
      <ng-content select="foo"></ng-content>
    </section>
    <section>
      <h3>tag selector(main, aside)</h3>
      <ng-content select="main"></ng-content>
      <ng-content select="aside"></ng-content>
    </section>
    <section>
      <h3>attribute selector</h3>
      <ng-content select="[hoge]"></ng-content>
    </section>
    <section>
      <h3>class selector</h3>
      <ng-content select=".hoge"></ng-content>
    </section>
    <section>
      <h3>others</h3>
      <ng-content></ng-content>
    </section>

  `,
})
export class Bar {

}

という風に定義して、使う側は以下のように書くと

<bar>
  <main>Main text</main>
  <aside>description</aside>
  <div>other1</div>
  <div hoge>[hoge]</div>
  <div>other2</div>
  <foo>foo</foo>
  <div>other3</div>
  <div class="hoge">.hoge</div>
  <div>other4</div>
</bar>

それぞれの<ng-content select="...">selectに設定されたセレクターに対応した要素が配置されて、残りの要素は無印の<ng-content></ng-content>が置いてある場所に格納されていきます。ちなみに、main2つ置いたら2とも置かれました。

selectで使えるセレクターは割と複雑なものが使えます。div[hoge]:not(.foo)みたいなのもいけました。多分ですが、これはdirectiveのselectorで使えるものと同等かと思われます。

参考

Transclusion in Angular 2 @toddmotto
ブログ記事はあるがなぜかangular.ioには全然ドキュメントがないんですよね…。

26
24
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
26
24