Mad*_*jan 24 typescript angular
我可以使用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);
});
}
}
Run Code Online (Sandbox Code Playgroud)
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("");
}
}
Run Code Online (Sandbox Code Playgroud)
所以在上面的例子中说loadChild
是按一下按钮调用,我可以加载Child1Component,但是如何传递var1
child的输入?另外如何订阅close
装饰的EventEmitter@Output
Gün*_*uer 41
你必须像以下那样强制通过它:
loadChild(): void {
this._cr.resolveComponent(Child1Component).then(cmpFactory => {
let cmpRef = this.childContainer.createComponent(cmpFactory);
cmpRef.instance.var1 = someValue;
});
}
Run Code Online (Sandbox Code Playgroud)
也类似于为输出注册处理程序.
loadChild(): void {
this._cr.resolveComponent(Child1Component).then(cmpFactory => {
let instance: any = this.childContainer.createComponent(cmpFactory).instance;
if (!!instance.close) {
// close is eventemitter decorated with @output
instance.close.subscribe(this.close);
}
});
}
close = (): void => {
// do cleanup stuff..
this.childContainer.clear();
}
Run Code Online (Sandbox Code Playgroud)
这就是我使用Angular 2.2.3做到的方式
let nodeElement = document.getElementById("test");
let compFactory = this.componentFactoryResolver.resolveComponentFactory(AnyCustomComponent);
let component = compFactory.create(this.viewContainerRef.injector, null, nodeElement);
// This is where you pass the @Input
component.instance.anyInput = anyInput;
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
16116 次 |
最近记录: |