Angular の@ViewChildの使い方

Angular の@ViewChildの使い方

Angular の@ViewChildを使えば、parent to view child というように親コンポーネントから子コンポーネントのメソッドなどにアクセスできるようになります。

またコンポーネントの#変数にアクセスできるようになります。

例えば子要素の数を知りたい場合、親要素に#変数を付加します。この変数がViewChildと紐づきます。

app.component.html

<div #aaa>
  <ul>
    <li></li>
    <li></li>
  </ul>
</div>
<button type='button' (click)='onTest()'>ボタン</button>

app.component.ts

import { Component, ViewChild, ElementRef} from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  @ViewChild('aaa') ppp: ElementRef;
  public onTest() {
    const elem: Element = this.ppp.nativeElement;// これがdivタグを指す
    alert(elem.childElementCount); // 子要素の数を取得する
  }
}

onTestイベントハンドラが@ViewChildを使ってdivタグの情報を取得できているのがわかります。

参考サイト

コメント

タイトルとURLをコピーしました