处理Angular 2中动态创建的Component的@Input和@Output

时间:2016-11-02 14:22:06

标签: javascript angular angular2-routing angular2-template

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

当调用 createSub 方法时,想法是动态创建(在本例中) SubComponent 。很好,但我如何为 SubComponent 中的@Input属性提供数据。另外,如何处理/订阅SubComponent提供的@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();
}

5 个答案:

答案 0 :(得分:4)

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

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即可订阅它,只要你emit()来自组件的值,你传入的clojure就会执行。

答案 1 :(得分:0)

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)
 }    
}

答案 2 :(得分:0)

我发现以下代码从字符串(angular2 generate component from just a string)动态生成组件,并从中创建了一个传递输入数据的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>

希望这可以为我节省大量的谷歌搜索。

答案 3 :(得分:-1)

如果您知道要添加的组件类型,我认为您可以使用其他方法。

在您的应用根组件html中:

 ((HttpsURLConnection) conn).setSSLSocketFactory(Common
                                    .getSSL().getSocketFactory()

在您的应用根组件打字稿中:

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

答案 4 :(得分:-1)

为@Input提供数据非常简单。您已将组件命名为app-sub,并且它具有名为data的@Input属性。提供此数据可以通过以下方式完成:

ng-options