0

你好我正在对gridster2做动态组件,我在“组件[this.componentRef];”中有问题 向我显示此错误:元素隐含地具有“任何”类型,因为“任何”类型的表达式不能用于索引类型“{ example1:typeof Example1Component; 示例 2:示例 2 组件的类型;}'

请有任何帮助

import { Directive, Input, OnChanges, ViewContainerRef, ComponentFactoryResolver, ComponentRef } from '@angular/core';

import {Example1Component} from '../../../Components/example1/example1.component';
import {Example2Component} from '../../../Components/example2/example2.component';
const components = {
  example1: Example1Component,
  example2: Example2Component
};
@Directive({
  selector: '[appLayoutItem]'
})
export class LayoutItemDirective implements OnChanges {
  @Input() componentRef!: any;
  component!: ComponentRef<any>;

  constructor(
    private container: ViewContainerRef,
    private resolver: ComponentFactoryResolver
  ) { }
  ngOnChanges(): void {
    const component = components[this.componentRef];

    if (component) {
      const factory = this.resolver.resolveComponentFactory<any>(component);
      this.component = this.container.createComponent(factory);
    }
  }
}
4

1 回答 1

0

我不太确定你到底想实现什么,但对我来说它应该是这样的(由于缺乏进一步的信息,我没有尝试这段代码)。

const components = {
  example1: Example1Component,
  example2: Example2Component
}; 

@Input() componentRef!: 'example1' | 'example2'; // 
 component!: ComponentRef<Example1Component | Example2Component>;

那么这个访问应该真的有效:

 const component = components[this.componentRef];

您可以考虑为“example1”使用枚举 | 'example2'也是如此,这是我个人喜欢做的,但这是个人喜好。

于 2021-03-09T09:16:00.470 回答