有没有办法从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