在Angular 2中为动态创建的组件处理@Input和@Output

Handle @Input and @Output for dynamically created Component in Angular 2

本文关键字:处理 组件 @Input @Output 创建 Angular 动态      更新时间:2023-09-26

如何为Angular 2中动态创建的组件处理/提供@Input@Output属性?

这个想法是在调用createSub方法时动态创建子组件。分叉很好,但是我如何为子组件中的@Input属性提供数据?此外,如何处理/订阅子组件提供的@Output事件?

例子:(两个组件都在同一个NgModule中)

AppComponent

@Component({
  selector: 'app-root'
})  
export class AppComponent {
  someData: 'asdfasf'
  constructor(private resolver: ComponentFactoryResolver, private location: ViewContainerRef) { }
  createSub() {
    const factory = this.resolver.resolveComponentFactory(SubComponent);
    const ref = this.location.createComponent(factory, this.location.length, this.location.parentInjector, []);
    ref.changeDetectorRef.detectChanges();
    return ref;
  }
  onClick() {
    // do something
  }
}

子组件

@Component({
  selector: 'app-sub'
})
export class SubComponent {
  @Input('data') someData: string;
  @Output('onClick') onClick = new EventEmitter();
}

您可以在创建组件时轻松地绑定它:

createSub() {
    const factory = this.resolver.resolveComponentFactory(SubComponent);
    const ref = this.location.createComponent(factory, this.location.length, this.location.parentInjector, []);
    ref.someData = { data: '123' }; // send data to input
    ref.onClick.subscribe( // subscribe to event emitter
      (event: any) => {
        console.log('click');
      }
    )
    ref.changeDetectorRef.detectChanges();
    return ref;
  }

发送数据非常简单,只需执行ref.someData = data,其中data是您希望发送的数据。

从输出中获取数据也很容易,因为它是一个EventEmitter,您可以简单地订阅它,并且您传入的clojure将在您从组件中emit()获取值时执行。

我发现下面的代码从字符串(angular2生成组件从只是一个字符串),并创建了一个compileBoundHtml指令从它传递输入数据(不处理输出,但我认为同样的策略将适用,所以你可以修改这个):

    @Directive({selector: '[compileBoundHtml]', exportAs: 'compileBoundHtmlDirective'})
export class CompileBoundHtmlDirective {
    // input must be same as selector so it can be named as property on the DOM element it's on
    @Input() compileBoundHtml: string;
    @Input() inputs?: {[x: string]: any};
    // keep reference to temp component (created below) so it can be garbage collected
    protected cmpRef: ComponentRef<any>;
    constructor( private vc: ViewContainerRef,
                private compiler: Compiler,
                private injector: Injector,
                private m: NgModuleRef<any>) {
        this.cmpRef = undefined;
    }
    /**
     * Compile new temporary component using input string as template,
     * and then insert adjacently into directive's viewContainerRef
     */
    ngOnChanges() {
        class TmpClass {
            [x: string]: any;
        }
        // create component and module temps
        const tmpCmp = Component({template: this.compileBoundHtml})(TmpClass);
        // note: switch to using annotations here so coverage sees this function
        @NgModule({imports: [/*your modules that have directives/components on them need to be passed here, potential for circular references unfortunately*/], declarations: [tmpCmp]})
        class TmpModule {};
        this.compiler.compileModuleAndAllComponentsAsync(TmpModule)
          .then((factories) => {
            // create and insert component (from the only compiled component factory) into the container view
            const f = factories.componentFactories[0];
            this.cmpRef = f.create(this.injector, [], null, this.m);
            Object.assign(this.cmpRef.instance, this.inputs);
            this.vc.insert(this.cmpRef.hostView);
          });
    }
    /**
     * Destroy temporary component when directive is destroyed
     */
    ngOnDestroy() {
      if (this.cmpRef) {
        this.cmpRef.destroy();
      }
    }
}
重要的修改是增加了:
Object.assign(this.cmpRef.instance, this.inputs);

基本上,它将你想要在新组件上的值复制到tmp组件类中,以便它们可以在生成的组件中使用。

可以这样使用:

<div [compileBoundHtml]="someContentThatHasComponentHtmlInIt" [inputs]="{anInput: anInputValue}"></div>

希望这能帮你省去大量的谷歌搜索。

createSub() {
  const factory = this.resolver.resolveComponentFactory(SubComponent);
  const ref = this.location.createComponent(factory, this.location.length, 
  ref.instance.model = {Which you like to send}
  ref.instance.outPut = (data) =>{ //will get called from from SubComponent} 
  this.location.parentInjector, []);
  ref.changeDetectorRef.detectChanges();
return ref;
}
SubComponent{
 public model;
 public outPut = <any>{};  
 constructor(){ console.log("Your input will be seen here",this.model) }
 sendDataOnClick(){
    this.outPut(inputData)
 }    
}

如果你知道你想要添加的组件的类型,我认为你可以使用另一种方法。

在你的应用根组件html:

<div *ngIf="functionHasCalled">
    <app-sub [data]="dataInput" (onClick)="onSubComponentClick()"></app-sub>
</div>

在你的应用根组件typescript中:

private functionHasCalled:boolean = false;
private dataInput:string;
onClick(){
   //And you can initialize the input property also if you need
   this.dataInput = 'asfsdfasdf';
   this.functionHasCalled = true;
}
onSubComponentClick(){
}

为@Input提供数据非常容易。你已经将你的组件命名为app-sub,它有一个名为data的@Input属性。可以这样提供这些数据:

<app-sub [data]="whateverdatayouwant"></app-sub>