Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular: passing data back from dynamic component

Based on an example in the cookbook, I am creating components dynamically like this:

    private loadComponent(): void {
        const componentFactory = this.factoryResolver.resolveComponentFactory(MyInputComponent);

        const viewContainerRef = this.componentHost.viewContainerRef;
        viewContainerRef.clear();

        const componentRef = viewContainerRef.createComponent(componentFactory);
        (<IComponent>componentRef.instance).data = data;
}

MyInputComponent's template would look like this:

<input type="text" [(ngModel)]="data.inputProp">

I need to update the value of data.inputProp in the parent when the user types in the input.

I have seen this in some examples, but not sure what it does?

componentRef.changeDetectorRef.detectChanges();

I've also read about subscribing to a child's EventEmitter in the parent, but only seen examples of that using click events. What is the better approach for updating all kinds of data including text inputs back to the parent?

I am using Angular 4 RC3

like image 225
Thibs Avatar asked Dec 04 '25 15:12

Thibs


1 Answers

If you want to send data to dynamically created component.

this.componentRef.instance.variableName = 'abc';  // here variableName is a variable of dynamic component.

If you want to get data from dynamically created component.

this.componentRef.instance.observeVariable.subscribe(result => { this.v = result;  // here observeVariable is an Observable in dynamic component(ie. this.componentRef).
like image 183
amansoni211 Avatar answered Dec 07 '25 12:12

amansoni211