![](/img/trans.png)
[英]Element implicitly has an 'any' type because expression of type '"logo"' can't be used to index type 'Object' in Angular
[英]Element implicitly has an 'any' type because expression of type 'any' can't be used to index type any one can tell me
你好我正在对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);
}
}
}
我不太确定你到底想达到什么目标,但对我来说它应该是这样的(由于缺乏进一步的信息,我没有尝试这段代码)。
const components = {
example1: Example1Component,
example2: Example2Component
};
@Input() componentRef!: 'example1' | 'example2'; //
component!: ComponentRef<Example1Component | Example2Component>;
那么这个访问应该真的有效:
const component = components[this.componentRef];
您可以考虑为“example1”使用枚举 | 'example2'也是如此,这是我个人喜欢做的,但这是个人喜好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.