我可以使用ComponentResolver和ViewContainerRef加载动态Angular 2组件 .
但是我无法弄清楚如何将子组件的任何输入变量传递给它 .
parent.ts
@Component({
selector: "parent",
template: "<div #childContainer ></div>"
})
export class ParentComponent {
@ViewChild("childContainer", { read: ViewContainerRef }) childContainer: ViewContainerRef;
constructor(private viewContainer: ViewContainerRef, private _cr: ComponentResolver) {}
loadChild = (): void => {
this._cr.resolveComponent(Child1Component).then(cmpFactory => {
this.childContainer.createComponent(cmpFactory);
});
}
}
child1
@Component({
selector: "child1",
template: "<div>{{var1}}</div><button (click)='closeMenu()'>Close</button>"
})
export class Child1Component {
@Input() var1: string;
@Output() close: EventEmitter<any> = new EventEmitter<any>();
constructor() {}
closeMenu = (): void => {
this.close.emit("");
}
}
所以在上面的例子中说 loadChild
正在点击一个按钮被调用,我可以加载Child1Component,但如何传递 var1
孩子的输入?另外如何订阅用 @Output
装饰的 close
EventEmitter
2 回答
你必须像以下那样强制通过它:
也类似于为输出注册处理程序 .
这是我用Angular 2.2.3做的