Javascript 角度-通过名称(非类型)创建动态组件
我有一个类型数组:Javascript 角度-通过名称(非类型)创建动态组件,javascript,angular,Javascript,Angular,我有一个类型数组:types=[C3,C1,C2]其中C1、C2、C3为类别: export class C1 {} //... C2 and C3 @Component({ selector: 'c2', //... C2 and C3 template: `<h2>c2</h2>` //... C2 and C3 }) : 但假设数组包含类型名称: 为了使'C3'成为C3,我应该在代码中做哪些更改 @yurzui确实如此,但
types=[C3,C1,C2]代码>其中C1、C2、C3为类别:
export class C1 {} //... C2 and C3
@Component({
selector: 'c2', //... C2 and C3
template: `<h2>c2</h2>` //... C2 and C3
})
:
但假设数组包含类型名称:
为了使'C3'
成为C3
,我应该在代码中做哪些更改
@yurzui确实如此,但那里的答案提到我必须使用名称和类型的词典(用于缩小)。所以我问-有没有一种方法可以将字符串“解析”为一个类型而不提及类型?(这是冗余的非动态解决方案)
@Component({
selector: 'my-app',
directives: [Tabs],
template: `
<my-tabs [tabs]="types"></my-tabs>
`
})
export class App {
// The list of components to create tabs from
types = [C3,C1,C2];
}
@Component({
selector: 'my-tabs',
directives: [DclWrapper],
template: `
<div *ngFor="let tab of tabs">
<dcl-wrapper [type]="tab"></dcl-wrapper>
</div>
`
})
export class Tabs {
@Input() tabs;
}
@Component({
selector: 'dcl-wrapper',
template: `<div #target></div>`
})
export class DclWrapper {
@ViewChild('target', {read: ViewContainerRef}) target;
@Input() type;
cmpRef:ComponentRef;
constructor(private componentFactoryResolver: ComponentFactoryResolver,
private cdRef:ChangeDetectorRef) {}
updateComponent() {
let factory = this.componentFactoryResolver.resolveComponentFactory(this.type);
this.cmpRef = this.target.createComponent(factory)
this.cdRef.detectChanges();
}
ngOnChanges() {
this.updateComponent();
}
ngOnDestroy() {
console.log('ngOnDestroy');
this.cmpRef.destroy();
}
}
}
types = [C3,C1,C2];
types = ['C3','C1','C2'];