István
István

Reputation: 5127

How to add dynamically FormControl to FormGroup

I have this plunker. I am creating form components dynamically, based on model (defined in app.ts), and cannot add

formControlName = "name"

to the component. In the control-factory.directive.ts I add

this.form.addControl(this.model.name, new FormControl());,

but how can I bind the value?

Upvotes: 3

Views: 31923

Answers (1)

yurzui
yurzui

Reputation: 214305

To keep form value in sync with your custom model i would subscribe to control.valueChanges

let control = new FormControl(this.model.data);
control.valueChanges.subscribe(x => {
  this.model.data = x;
});
this.form.addControl(this.model.name, control);

to keep in sync form model and view i would bind FormControl to reactive directive i.e. formControl

datepicker.component.html

<input [formControl]="form.get(model.name)">

Modified Plunker

Upvotes: 15

Related Questions