3
1

More than 5 years have passed since last update.

【Angular.io】Displaying Data まとめ

Posted at

Displaying Data

この章ではモデルからビューへどのようにデータを出力するかの説明をします。

  • インターポレーション (Interpolation)
  • テンプレート or テンプレートファイル
  • コンストラクタ or 変数の初期化
  • *ngForを使ったデータ出力
  • クラスを用いたデータ出力
  • NgIfで条件分岐

インターポレーション (Interpolation)

インターポレーションでは、テンプレート内でクラスのプロパティを表示する場所を指定する。以下では、 AppComponenttitlemyHero を ビュー側で {{ title }}{{ myHero }} と書くことによって各プロパティの値をビューに反映させることができる。

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
    <h1>{{title}}</h1>
    <h2>My favorite hero is: {{myHero}}</h2>
    `
})
export class AppComponent {
  title = 'Tour of Heroes';
  myHero = 'Windstorm';
}

Angularは自動的にコンポーネントから titlemyHero の値を取得してビューに反映させる。プロパティの値が変更されたら、その変更された値を検知して都度ビューへ渡す仕組み。

AppComponent のインスタンスはどのタイミングでできるかというと、html内にある <my-app></my-app> が読み込まれたときに、AppComponent クラスのインスタンスを生成して、それに紐づくテンプレートを <my-app> 内に出力する。

テンプレート or テンプレートファイル?

コンポーネントのメタデータとして指定するテンプレートは、インラインで記述する方法とファイルパスで指定する方法がある。

インラインで指定する方法

@Component({
  selector: 'my-app',
  template: `
    <h1>{{title}}</h1>
    <h2>My favorite hero is: {{myHero}}</h2>
    `
})

ファイルパスで指定する方法

@Component({
  selector: 'my-app',
  templateUrl: ‘my-app.component.html'
})

コンストラクタ or 変数の初期化?

コンストラクタ内でクラスのプロパティに初期値を代入することができる。

export class AppCtorComponent {
  title: string;
  myHero: string;

  constructor() {
    this.title = 'Tour of Heroes';
    this.myHero = 'Windstorm';
  }
}

*ngForを使ったデータ出力

配列をビュー側で出力するには、*ngFor を使用することができる。

export class AppComponent {
  title = 'Tour of Heroes';
  heroes = ['Windstorm', 'Bombasto', 'Magneta', 'Tornado'];
  myHero = this.heroes[0];
}

heroes リストをビューで表示させる

template: `
  <h1>{{title}}</h1>
  <h2>My favorite hero is: {{myHero}}</h2>
  <p>Heroes:</p>
  <ul>
    <li *ngFor="let hero of heroes">
      {{ hero }}
    </li>
  </ul>
`

クラスを用いたデータ出力

実際のデータはただの配列だけでなく複雑なオブジェクトを含むことがある。そのようなデータも *ngFor で出力可能。

heroes をクラス化させる

export class Hero {
  constructor(
    public id: number,
    public name: string) { }
}

heroes にインスタンスを生成

heroes = [
  new Hero(1, 'Windstorm'),
  new Hero(13, 'Bombasto'),
  new Hero(15, 'Magneta'),
  new Hero(20, 'Tornado')
];
myHero = this.heroes[0];

ビューで出力

template: `
  <h1>{{title}}</h1>
  <h2>My favorite hero is: {{myHero.name}}</h2>
  <p>Heroes:</p>
  <ul>
    <li *ngFor="let hero of heroes">
      {{ hero.name }}
    </li>
  </ul>
`

NgIfで条件分岐

ngIf を使用すると、データの出力を与えられた条件のもと操作することができる。

<p *ngIf="heroes.length > 3">There are many heroes!</p>

heroes が4つ以上だったら出力して、heroesが3以内だったら出力しない。*ngIf はfalseだったときは、DOM自体を消してしまうが、[hidden] を使用するとDOM自体は存在する。

<p [hidden]="heroes.length < 3">There are many heroes!</p>

参考:
https://angular.io/guide/displaying-data

3
1
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
3
1