简体   繁体   中英

Element implicitly has an 'any' type because expression of type 'any' can't be used to index type any one can tell me

hello im doing dynamic component to gridster2 and i have a problem in "components[this.componentRef];"is show me this error:Element implicitly has an 'any' type because expression of type 'any' can't be used to index type '{ example1: typeof Example1Component; example2: typeof Example2Component; }'

any help please

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);
    }
  }
}

I'm not really sure what exactly you are tring to achieve, but to me it looks like it should be like this (I did not try this code due to the lack of further information).

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

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

Then this access should actually work:

 const component = components[this.componentRef];

You could consider using an Enum for 'example1' | 'example2' as well, that's what I personally like to do but it's personal preference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM