【问题标题】:Giving an @input to a dynamically loaded component in Angular在 Angular 中为动态加载的组件提供 @input
【发布时间】:2021-08-31 19:23:47
【问题描述】:

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

 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;

  }

}

但是,在带有 cmets 注释的行中,我收到了错误消息

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

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

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

谁能指出我在编译时不知道类型的任何方法?或者如果我以错误的方式动态创建组件。

提前谢谢你。

【问题讨论】:

  • 您好,您可以使用 prop 方法,但它不是类型安全的。您可以尝试在输入装饰器上指定组件的类型吗?

标签: angular typescript dynamic components


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-19
    • 2017-09-11
    • 2020-04-17
    • 2019-02-06
    • 1970-01-01
    • 2016-08-01
    • 1970-01-01
    • 2016-08-15
    相关资源
    最近更新 更多