2019年2月10日日曜日

Angular @ViewChild デコレーター

Angular では、HTML テンプレート上に定義されているコンポーネントを TypeScript 側から参照する機能として、@ViewChild デコレーターが提供されています。

例えば、AppComponent に次の MyLabelComponent を利用しているとします。


MyLabelComponent (TypeScript)
import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-my-label',
  templateUrl: './my-label.component.html',
  styleUrls: ['./my-label.component.css']
})
export class MyLabelComponent {
  constructor() { }
  @Input('text') text: string;
}
MyLabelComponent (HTML テンプレート)
<p>
  my-label works! {{text}}
</p>

AppComponent の TypeScript 上で、@ViewChild デコレーターに型を指定するかたちで、MyLabelComponent を参照することができます。

AppComponent (TypeScript)
import { Component, ViewChild } from '@angular/core';
import { MyLabelComponent } from './my-label/my-label.component';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app1';

  @ViewChild(MyLabelComponent) myLabel: MyLabelComponent;

  getText() {
    console.log(this.myLabel.text);
  }
}

AppComponent (HTML テンプレート)
<app-my-label text="abc"></app-my-label>


なお、複数の MyLabelComponent が存在する場合、 テンプレート参照変数を利用してコンポーネントを特定します。(この例では、HTML テンプレート上の #label1 や #label2 がテンプレート参照変数です。)

 AppComponent (TypeScript)
export class AppComponent {
  title = 'app1';

  @ViewChild('label1') myLabel1: MyLabelComponent;
  @ViewChild('label2') myLabel2: MyLabelComponent;

  getText() {
    console.log(this.myLabel1.text);
    console.log(this.myLabel2.text);
  }
}

AppComponent (HTML テンプレート)
<app-my-label #label1 text="abc"></app-my-label>
<app-my-label #label2 text="def"></app-my-label>


Angular に関連するトピックは次のページにまとめてあります。

Angular 機能紹介一覧
https://kainobi2.blogspot.com/2019/02/angular.html

0 件のコメント:

コメントを投稿