Angular 5 - 获取给定页面/视图的订单号的所有组件名称

时间:2018-01-30 00:01:15

标签: angular angular5 angular-components

有没有办法从DOM获取 组件名称

例如,如果我的app.component.html是:

<div>
  <div #leftContainer>
     <app-hello></app-hello>
     <app-foo></app-foo>
  </div>
  <div #rightContainer>
    <app-bar></app-bar>
    <app-foobar><app-foobar>
  </div>
</div>

GetComponents的输出应为:

1-HelloComponent
2-FooComponent
3-BarComponent
4-FooBarComponent

app.component.ts

import { Component, ViewChild, ViewContainerRef } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  @ViewChild('leftContainer', { read: ViewContainerRef }) leftContainer: ViewContainerRef;
  @ViewChild('rightContainer', { read: ViewContainerRef }) rightContainer: ViewContainerRef;

  name = 'Angular 5';

  getComponents() {
    for (let i = 0; i < this.leftContainer.length; i++) {
      console.log(this.leftContainer.get(i));
    }
  }
}

完整示例位于以下StackBlitz网址: https://stackblitz.com/edit/angular-weyhe4

0 个答案:

没有答案