君は心理学者なのか?

大学時代に心理学を専攻しなぜかプログラマになった、サイコ(心理学)プログラマかろてんの雑記。

angular2で親componentから子componentへ値を受け渡す方法

angular2で親componentから子componentへ値を受け渡す

0. 準備

新規プロジェクトを作成し、サーバをスタートさせます。

ng new deliver-property
ng serve

1. 親コンポーネントとテンプレートに以下を記述

// app.component.ts
export class AppComponent {
  private deliverProperty: string = '子供に送るよ。';
  private notDeliverProperty: string = '子供に送らないよ。';
}
<!-- app.component.html -->
<h1>親コンポーネント</h1>
<ul>
  <li>{{deliverProperty}}</li>
  <li>{{notDeliverProperty}}</li>
</ul>

定義した2つのプロパティのうち、 deliverPropertyを子コンポーネントに渡すことにします。

2. 親コンポーネントのテンプレートに、コンポーネントへ渡したい変数を書く

今回、

  • app component の deliverProperty を
  • child component に
  • parentPropertyとして

渡したいとします。

<!-- app.component.html -->
<h1>親コンポーネント</h1>
<ul>
  <li>{{notDeliverProperty}}</li>
  <li>{{deliverProperty}}</li>
</ul>

<app-child [parentProperty]="deliverProperty"></app-child>

3. 子コンポーネントを生成

ng g component child

4. 子コンポーネントにてInputを記述

以下の2箇所を記述します。

// child.component.ts
import {
  Component,
  OnInit,
  Input // ←その1
} from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {

  @Input() parentProperty; // ←その2
  constructor() { } 

  ngOnInit() {
  }

}

その2には、 親から渡される変数名ではなく、子で使う変数名を記述します。

5. 子コンポーネントのテンプレートに変数を記述

<!-- child.component.html -->
<h1>子コンポーネント</h1>
<p>{{parentProperty}}</p>

結果

f:id:karoten512:20170901103758p:plain