[英]Giving an @input to a dynamically loaded component in Angular
I am trying to dynamically create components based on a string, and the dynamic components will have @Input fields that are needed from the parent.我正在尝试基于字符串动态创建组件,并且动态组件将具有父级所需的 @Input 字段。 Here is a snippet of how I am dynamically creating the components
这是我如何动态创建组件的片段
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;
}
}
However, on the lines annotated with comments saying there is an error, I am receiving但是,在注释有错误的注释的行中,我收到了
'Property data1 does not exist on type 'unknown''
Issue: All of the dynamic components will adhere to having these properties, however at the time of compilation the component loader will not know that the component contains the property,问题:所有动态组件都将坚持拥有这些属性,但是在编译时组件加载器将不知道组件包含该属性,
If I were to supply the name of the component directly into the resolveComponentFactory as opposed to 'this.dynamicComponentName', then the error will not be there.如果我将组件的名称直接提供给 resolveComponentFactory 而不是“this.dynamicComponentName”,则不会出现错误。 But this obviously is what I'm trying to avoid as the dynamic component name will always be different.
但这显然是我试图避免的,因为动态组件名称总是不同的。
Could anyone point me to any way to resolve having the type not be known at compile time?谁能指出我在编译时不知道类型的任何方法? Or if I am dynamically creating the components in a wrong way.
或者,如果我以错误的方式动态创建组件。
Thank you in advance.先感谢您。
You could probably use the ['prop']
notation instead of the dot notation to access the input
properties so typescript doesn't complain.您可能可以使用
['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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.