英文:
generate angular componenet based generic paramter
问题
For a dialog component that contains a generic parameter for a child component, is there a way to use ViewContainerRef.createComponent
based on the generic parameter T
?
Code:
export class CustomModal<T extends Component> implements OnInit {
// ...
@ViewChild('container')
public container: ViewContainerRef;
loadComponent(): void {
let child = this.container.createComponent(T);
// Error: 'T' only refers to a type, but is being used as a value here.ts(2693)
}
}
我明白了。在这个代码中,您遇到了一个错误:'T' 只被用作类型,不能在这里用作值。这是因为 TypeScript 中的泛型参数 T
在运行时不可用,只能在编译时用于类型检查。如果您想要根据泛型参数创建组件实例,您需要传递一个具体的组件类而不是泛型参数 T
。
英文:
for a dialog component , that contain generic parameter of child component.
is there any way to use ViewContainerRef.createComponent
based on generic Parameter (for example: T
),
for this code :
export class CustomModal<T extends Component > implements OnInit {
......
@ViewChild('container')
public container: ViewContainerRef;
loadComponent(): void {
let child= this.container.createComponent(T);
//Error: 'T' only refers to a type, but is being used as a value here.ts(2693)
}
I have go this error:
'T' only refers to a type, but is being used as a value here.ts(2693)
答案1
得分: 1
You should use Type<any>
instead of T
.
Alternatively, you can create a common parent class (ex: AppDynamicComponent
) for all your dynamic child components to extend, and then use Type<AppDynamicComponent>
.
The createComponent
APIs take Type<C>
as input for the component
parameter, according to the docs:
- https://angular.io/api/core/createComponent
- https://angular.io/api/core/ViewContainerRef#createComponent
Type<>
can be imported from '@angular/core'
.
Side-note: Type<>
is the same thing that Injector.get()
takes as input.
Example Stackblitz application: https://stackblitz.com/edit/angular-zy69nc?file=src/child.model.ts
英文:
You should use Type<any>
instead of T
.
Alternatively, you can create a common parent class (ex: AppDynamicComponent
) for all your dynamic child components to extend, and then use Type<AppDynamicComponent>
.
The createComponent
APIs take Type<C>
as input for the component
parameter, according to the docs:
- https://angular.io/api/core/createComponent
- https://angular.io/api/core/ViewContainerRef#createComponent
Type<>
can be imported from '@angular/core'
.
Side-note: Type<>
is the same thing that Injector.get()
takes as input.
Example Stackblitz application:https://stackblitz.com/edit/angular-zy69nc?file=src/child.model.ts
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论