After successfully loading a dynamic Angular 2 component using ComponentResolver and ViewContainerRef, I am faced with the challenge of passing input variables from the parent component to the child component.
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("");
}
}
In the scenario described above where loadChild
is triggered by a button click, the challenge remains on how to effectively pass the value of var1
as an input into the child component. Additionally, subscription to the close
EventEmitter decorated with @Output
needs to be implemented.