3

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

Community
  • 1
  • 1
Thibs
  • 8,058
  • 13
  • 54
  • 85
  • Are you loading components dynamically or is it a pre-created component? – Gary Mar 17 '17 at 03:15
  • Thanks for your time Gary, the instances of the components are craeted and loaded dynamically – Thibs Mar 17 '17 at 03:38
  • detectChanges() will trigger manual change detection. http://stackoverflow.com/questions/34827334/triggering-angular2-change-detection-manually – Gary Mar 17 '17 at 05:43

1 Answers1

5

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).
Gi1ber7
  • 632
  • 1
  • 11
  • 22
amansoni211
  • 889
  • 2
  • 13
  • 30
  • cool. does that mean you are asking the observeVariabel to be created as an observable? I was tying this out with events through services and seems like you cannot inject a service to a dynamic component. It gives zone error. How do you suggest create an observable for the variable here. observable.create or behavioursubject? – Gary Mar 17 '17 at 04:56
  • observeVariable: Subject = new Subject(); will do the trick – amansoni211 Mar 17 '17 at 05:02
  • Ok let me try this. Is this supposed to be in the service or from the dynamic component? – Gary Mar 17 '17 at 05:43
  • it will be from dynamic component. – amansoni211 Mar 17 '17 at 05:52
  • Thanks for reply. How can I hook up that subject in the dynamic component to a text input which next's each key change? I miss ng-include and bindings... – Thibs Mar 17 '17 at 10:55
  • juat get the input's value in a variable and ngOnChange function pass that varibale in subject.next() and you'll get the value. – amansoni211 Mar 19 '17 at 06:45