LoginSignup
10
10

More than 5 years have passed since last update.

Angular2でComponentを再帰的に処理する

Posted at

Componentを再帰的に処理したいと思い、試してみたところ普通にできたのでやり方を紹介します
Objectの構造やディレクトリの表示とか再帰処理が必要なところで使えそうです
今回はObjectの構造を表示するサンプルです

再帰処理させたいComponent

@Component({
  selector: 'object-view',
  template: `
    <ul>
      <li *ngFor="#property of getKeys()">
        {{property}}: 
        <span *ngIf="!isObject(property)">
          {{getValue(property)}}
        </span>
        <span *ngIf="isObject(property)">
          <object-view [object]="getValue(property)"></object-view>
        </span>
      </li>
    </ul>
  `,
  directives: [ObjectViewComponent]
})
export class ObjectViewComponent {
  @Input() object: any;

  private getKeys(): string[] {
    return Object.keys(this.object);
  }

  private getValue(property: string): any {
    return this.object[property];
  }

  private isObject(property: string): boolean {
    const value = this.getValue(property);
    return !Array.isArray(value) && typeof value === 'object';
  }
}

directivesで自分自身を子Componentとして指定します
そして、templateの部分を見てもらうとわかりますが、プロパティの値がObjectだったら
自身のセレクターで指定したタグをレンダリングします
きちんとObjectかどうかの判定を入れないとブラウザが死ぬので注意w

あとは、親Componentで子Componentの@Inputディレクティブにobjectを渡すだけです

@Component({
  selector: 'my-app',
  template: `
    <object-view [object]="object"></object-view>
  `,
  directives: [ObjectViewComponent]
})
export class App {
  private object: any = {
    string: 'string',
    boolean: true,
    number: 0,
    array: ['a', 'b', 'c'],
    object: {
      prop1: 'prop1',
      prop2: 100
      prop3: {
        array: ['999', '998', '997']
      }
    }
  }
}

動作サンプル

まとめ

ハマるかと思ったけど、普通に再帰処理できる

10
10
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
10
10