@Output的Angular2 dynamiccomponentloader参数

时间:2016-05-01 05:48:47

标签: input angular output eventemitter

根据我的理解,您使用DynamicComponentLoader为刚添加到DOM的组件设置@Input变量的方式是在调用loadIntoLocation之后使用promise块:

this.dcl.loadIntoLocation( Lorem, this.elRef, 'target')
            .then( cmpRef => {

                cmpRef.instance.foo = _self.baz;
            });


export class Lorem {
    public @Input()  foo : String;
    ...

我的问题是你在使用dynamiccomponentloader时如何设置@Output?

this.dcl.loadIntoLocation( Lorem, this.elRef, 'target')
            .then( cmpRef => {

                cmpRef.instance.foo = _self.baz;
                cmpRef.instance.changer = _self.change($event);
            });



export class Lorem {
    public @Input()  foo            : String;
           @Output() changer = new EventEmitter();
    ...
    ...
    this.changer.emit("event");

我非常感谢您提供的帮助。

1 个答案:

答案 0 :(得分:3)

我会利用 subscribe 方法链接到_self.change($ event)函数的结果,如下所示:

cmpRef.instance.changer.subscribe(($event) => _self.change($event));

自从beta.16 loadIntoLocation被删除后,在我的例子中,我将使用loadNextToLocation,它将采用ViewContainerRef。

应用程序组件

import {Component, DynamicComponentLoader, ViewChild, ViewContainerRef} from 'angular2/core';

@Component({
  selector: 'my-app',
  providers: [],
  template: `
    <div>
      <h2>Hello {{name}}</h2>
      <div #target></div>
    </div>
  `,
  directives: []
})
export class App {
  baz: string = "Test string";
  @ViewChild('target', {read: ViewContainerRef}) target : ViewContainerRef;
  constructor(private dcl: DynamicComponentLoader) {
    this.name = 'Angular2'
  }
  ngAfterViewInit() {
    this.dcl.loadNextToLocation(Lorem, this.target)
      .then(cmpRef => {
        cmpRef.instance.foo = this.baz;
        cmpRef.instance.changer.subscribe(($event) => this.change($event));
      });
  }
  change($event) {
    alert($event);
  }
}

Lorem组件

import {Component, Input, Output, EventEmitter} from 'angular2/core';

@Component({
  selector: 'lorem',
  template: `
  <div>{{foo}}</div>
  <button (click)="run()">Run</button>`
})
class Lorem {
  @Input() foo: String;
  @Output() changer = new EventEmitter();
  run() {
    this.changer.emit("event from child");
  }
}

请参阅plunker example

希望它对你有所帮助。