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
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With