QueryListにQueryを追加したり、追加されたことを感知する

このエントリーをはてなブックマークに追加

やりたかったこととしてはViewChildrenContentChildrenで取得したQueryListにあらたなQuery情報を追加したり、追加されたことをQueryListのchanges.subscribeで検出するというです。

以下のサンプルではaddボタンを押された際にViewChildrenに情報を追加して、changes.subscribe()が発火するようにしています。

import {
  Component,
  QueryList,
  AfterViewInit,
  ViewChildren,
  ViewContainerRef
} from '@angular/core';

//child
@Component({
  selector: 'child',
  template: `<p>child</p>`
})
export class Child {}

//app-root
@Component({
  selector: 'app-root',
  template: `
     <template #tpl>
       <child></child>
     </template>
     <button (click)="add(tpl)">add</button>
  `,
})
export class AppRoot implements AfterViewInit{
  @ViewChildren(Child)children:QueryList<Child>;
  constructor(private vcr : ViewContainerRef) {}
  add(tpl) {
    this.vcr.createEmbeddedView(tpl);
    console.log("added",this.children.length);
  }
  ngAfterViewInit() {
    this.children.changes.subscribe((changes: any) => {
      console.log("changed",changes)
    })
  }
}

参考URL

Detecting dynamic additions - Plnkr

登録日 : 2017年02月02日 最終更新日 : 2017年2月2日

同じカテゴリー(TIPS)のエントリー

検索

スポンサードリンク

バージョン

リファレンス