0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Angular ng-content について

Posted at

概要

ng-content は、親コンポーネントから子コンポーネントへHTMLコンテンツを埋め込む仕組みである。
この機能は Content Projection(コンテンツ投影) と呼ばれ、コンポーネントの再利用性を高めるために使われる。

親コンポーネントから子コンポーネントにデータを渡す

親コンポーネントのビュー(View)で、コンテンツを渡したい子コンポーネントのセレクター名<app-child> をHTMLのタグとして指定する。

parent.component.html
<!-- 親コンポーネント (app-parent) のhtmlファイル-->
<!-- 親コンポーネントのセレクター名をタグに指定(app-parent) -->
<app-child> 
  <!-- 親から子コンポーネントへ渡すコンテンツ -->
  <p>親コンポーネントから渡されました</p>
</app-child>

そして、以下のように子コンポーネントのビュー(View)に <ng-content> を明記してあげることで、親コンポーネントから渡されたコンテンツが、子コンポーネントに表示される。

child.component.ts
// 子コンポーネント (app-child)のtsファイル
import { Component } from '@angular/core';

@Component({
  selector: 'app-child',  // 子コンポーネントのセレクター
  template: `
    <div class="child-container">
      <h3>子コンポーネント</h3>
      <!-- 親から渡されたコンテンツがここに表示される -->
      <ng-content></ng-content> 
    </div>
  `
})
export class ChildComponent {}

子コンポーネントで以下のように表示される。

子コンポーネント
親コンポーネントから渡されました

ここで出てくる疑問として、複数の渡したいコンテンツがあった場合、どうするかである。

複数のコンテンツを渡す例

親コンポーネントから複数の異なるコンテンツを子コンポーネントに渡したい場合、<ng-content>select属性を使用して、特定のコンテンツを特定の場所に投影することができる。

parent.component.html
<!-- 親コンポーネント (app-parent) のhtmlファイル-->
<app-child>
  <!-- 最初のコンテンツ -->
  <p class="content1">親からの最初のコンテンツ</p>
  
  <!-- 2番目のコンテンツ -->
  <p class="content2">親からの2番目のコンテンツ</p>
</app-child>

child.component.ts
// 子コンポーネント (app-child)のtsファイル
import { Component } from '@angular/core';

@Component({
  selector: 'app-child',  // 子コンポーネントのセレクター
  template: `
    <div class="child-container">
      <h3>子コンポーネント</h3>

      <!-- 最初のコンテンツをここに表示 -->
      <div class="content1-container">
        <ng-content select=".content1"></ng-content>
      </div>

      <!-- 2番目のコンテンツをここに表示 -->
      <div class="content2-container">
        <ng-content select=".content2"></ng-content>
      </div>
    </div>
  `
})
export class ChildComponent {}

子コンポーネントで以下のように表示される。

子コンポーネント
親からの最初のコンテンツ
親からの2番目のコンテンツ

まとめ

ng-contentは、親コンポーネントから子コンポーネントへコンテンツを埋め込む仕組み(コンテンツ投影)で、再利用性を高めるために使用される。複数のコンテンツを渡す場合、select属性を使い、異なる場所にコンテンツを投影でき、柔軟なレイアウトが実現可能になーる。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?