0

下面的代码在 Angular 13 中动态创建组件

指令:

import { Directive, Input, ViewContainerRef, Type } from '@angular/core';

@Directive({
  selector: '[appLoader]'
})
export class LoaderDirective {

  @Input() appLoader!: Type<any>;

  constructor(private viewContainerRef: ViewContainerRef) {}

  ngOnInit(): void {
    this.viewContainerRef.createComponent(this.appLoader);
  }

}

app.component.html

<div [appLoader]="component"></div>

app.component.ts

component = MyComponent

我还需要将一个对象传递给创建的组件,这是一些将由创建的组件使用的额外信息。

我怎样才能做到这一点?

4

1 回答 1

0

我想你的指令可能有点像

export class LoaderDirective {

  @Input() appLoader!: Type<any>;
  @Input() arg:any;  //<--you pass as arg any object

  //you need inject ComponentFactoryResolver
  constructor(private viewContainerRef: ViewContainerRef,
              private componentFactoryResolver: ComponentFactoryResolver) {}

  ngOnInit(): void {
    //first you "create" a component
    const component=this.componentFactoryResolver.resolveComponentFactory(this.appLoader)
    //in componentRef you get a instance of the component
    const componentRef=this.viewContainerRef.createComponent(component);

    //you can access to the component using componentRef.instance
    //e.g. componentRef.instance.someMethod()
    //     componentRef.instance.prop="what-ever"

    //I choose use the object pass in the "arg" Input
    Object.keys(this.arg).forEach(x=>{
      componentRef.instance[x]=this.arg[x]
    })
  }

你用喜欢

<div [appLoader]="component" [arg]="{name:'Angular'}"></div>

看一个傻瓜stackblitz

于 2021-11-22T09:38:33.727 回答