LoginSignup
2
2

More than 5 years have passed since last update.

Angular2(Angular4) > 子コンポーネントをViewChildenで取得して操作する

Last updated at Posted at 2017-08-10

こんにちわ、初投稿です。
最近Angular4でアプリ開発を行なっているのですが、日本語のドキュメントが(総量も)少なくて困ることがあるので、ちょっとしたAPIの使用方法を備忘録的に書いていこうと思います。

ViewChildrenで任意の子要素を操作する

ViewChildなら子要素が一個だけど、ViewChildrenは子要素がリストで取得できるので、所望の要素をどうやって抽出するべきか悩みました。でも、親コンポーネントが複数の子コンポーネントのインスタンスを持っていて、任意の子を操作したいことってありますよね。

まずViewChildrenの型は以下の通り
@ViewChildren ( {Compornent名} ) children: QueryList<{Component名}>

childrenの型はQueryListなんですね。なので、QueryListのAPIリファレンスを参照すればよかった。

結論

こんな感じに書くと特定の子コンポーネントのメソッドを実行できます。

// 子コンポーネント
export class ChildComponent{
  public id; // unique
  public hoge = function { ... };
}

// 親コンポーネント
export class ParentComponent{
  private activeComponentId = 1; // 任意の値
  @ViewChildren (ChildComponent) childComponents: QueryList<ChildrenComponent>;

  var hoge = () => {
    this.childComponents.find((component) => {
      return component.id === this.activeComponentId;
    }).hoge();
  }
}
2
2
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
2
2