I'm trying to build a component that appends another component dynamically. As an example here is my parent class:
import { Component, ComponentRef, ViewChild, ViewContainerRef, ComponentFactoryResolver } from '@angular/core';
@Component({
templateUrl: './app/sample-component.component.html',
selector: 'sample-component'
})
export class SampleComponent {
@ViewChild('dynamicContent', { read: ViewContainerRef })
protected dynamicComponentTarget: ViewContainerRef;
private currentComponent: ComponentRef<any>;
private selectedValue: any;
constructor(private componentResolver: ComponentFactoryResolver) {
}
private appendComponent(componentType: any) {
var factory = this.componentResolver.resolveComponentFactory(componentType);
this.currentComponent = this.dynamicComponentTarget.createComponent(factory);
}
}
sample-component.component.html:
<div #dynamicContent></div>
It works fine with appending an element, but i have no idea about how to bind two-way dynamically, like i do in static components: [(ngModel)]="selectedValue"
Two-way data binding in Angular will help users to exchange data from the component to view and from view to the component. It will help users to establish communication bi-directionally. Two-way data binding can be achieved using a ngModel directive in Angular.
Angular v2+ supports two-way data binding using ngModel directive and also by having getter and setter methods.
Two-way Data-Binding: In two-way data binding when there is a change in the model, the data values change is reflected in the view. This is also referred as “Dynamic Data Binding in AngularJS”.
Difference between One-way & Two-way Binding This means that the flow of code is from ts file to Html file as well as from Html file to ts file. In order to achieve one-way binding, we used the property binding concept in Angular. In order to achieve a two-way binding, we will use ngModel or banana in a box syntax.
Binding with dynamically added components is not supported.
You can use a shared service to communicate with dynamically added components (https://angular.io/docs/ts/latest/cookbook/component-communication.html)
or you can read/set imperatively using the this.currentComponent
reference:
private appendComponent(componentType: any) {
var factory = this.componentResolver.resolveComponentFactory(componentType);
this.currentComponent = this.dynamicComponentTarget.createComponent(factory);
this.currentComponent.instance.value = this.selectedValue;
this.currentComponent.instance.valueChange.subscribe(val => this.selectedValue = val);
}
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