生成基于通用参数的Angular组件。

huangapple go评论64阅读模式
英文:

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&lt;T extends Component &gt; implements OnInit {
......
@ViewChild(&#39;container&#39;)
  public container: ViewContainerRef;
  loadComponent(): void {
    let child= this.container.createComponent(T);
    //Error:  &#39;T&#39; only refers to a type, but is being used as a value here.ts(2693)
  }

I have go this error:

&#39;T&#39; only refers to a type, but is being used as a value here.ts(2693)

答案1

得分: 1

You should use Type&lt;any&gt; 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&lt;AppDynamicComponent&gt;.

The createComponent APIs take Type&lt;C&gt; as input for the component parameter, according to the docs:

Type&lt;&gt; can be imported from &#39;@angular/core&#39;.

Side-note: Type&lt;&gt; 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&lt;any&gt; 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&lt;AppDynamicComponent&gt;.

The createComponent APIs take Type&lt;C&gt; as input for the component parameter, according to the docs:

Type&lt;&gt; can be imported from &#39;@angular/core&#39;.

Side-note: Type&lt;&gt; is the same thing that Injector.get() takes as input.

Example Stackblitz application:https://stackblitz.com/edit/angular-zy69nc?file=src/child.model.ts

huangapple
  • 本文由 发表于 2023年5月11日 04:34:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/76222361.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定