在 Angular 中为动态加载的组件提供 @input

Giving an @input to a dynamically loaded component in Angular

我正在尝试基于字符串动态创建组件,动态组件将具有父级所需的@Input 字段。这是我如何动态创建组件的片段

 import { Component1 } from '../../Component1.component';

@Component({
...
})
export class DynamicContainerComponent implements OnInit {
  static map = {
    'COMP1': Component1,
    ... // more components
  }
  @Input() dynamicComponentName;
  @Input() data1;
  @Input() data2;
  @Input() data3;
  constructor(    
    private vcRef: ViewContainerRef, 
    private resolver: ComponentFactoryResolver) { }

  ngOnInit(): void {
    const componentFactory = this.resolver.resolveComponentFactory(DynamicContainerComponent.map[this.dynamicComponentName]);
    const dynamicComponent = this.vcRef.createComponent(paymentGatewayFactory);
    dynamicComponent.instance.data1 = this.data1; // errors on this line and below
    dynamicComponent.instance.data2 = this.data2;
    dynamicComponent.instance.data3 = this.data3;

  }

}

但是,在注释有错误的行上,我收到了

'Property data1 does not exist on type 'unknown''

问题:所有动态组件都将坚持具有这些属性,但是在编译时组件加载器将不知道该组件包含 属性、

如果我直接将组件名称提供给 resolveComponentFactory 而不是 'this.dynamicComponentName',那么错误就不会出现。但这显然是我要避免的,因为动态组件名称总是不同的。

任何人都可以指点我解决编译时类型未知的问题吗?或者如果我以错误的方式动态创建组件。

提前致谢。

您可以使用 ['prop'] 表示法而不是点表示法来访问 input 属性,这样 typescript 就不会报错。

ngOnInit(): void {
    const componentFactory = this.resolver.resolveComponentFactory(DynamicContainerComponent.map[this.dynamicComponentName]);
    const dynamicComponent = this.vcRef.createComponent(paymentGatewayFactory);

    // new
    dynamicComponent.instance['data1'] = this.data1;
    dynamicComponent.instance['data2'] = this.data2;
    dynamicComponent.instance['data3'] = this.data3;

    // you might need to trigger this too to make sure it runs change detection so the UI of the dynamic component gets updated
    dynamicComponent.changeDetectorRef.detectChanges();
}