VJAI
VJAI

Reputation: 32768

Attaching formControlName directive to a component created programatically

I've a library custom form components built in Angular 7. Each of this component is wrapper over native input, textarea, checkbox elements. I've implemented the ValueAccessor to make them work with ngModel and formControl/formControlName. Things works fine in the case of declarative use.

for ex.

<custom-textbox label="Name" required formControlName="name"></custom-textbox>

In my use-case, I've to create the custom form components dynamically from JSON and I've used ComponentFactoryResolver to accomplish that. My problem is when I create these custom form components dynamically how I can apply the formControlName directive to it. Any help would be greatly appreciated.

Upvotes: 0

Views: 377

Answers (1)

AVJT82
AVJT82

Reputation: 73377

Let's assume your JSON looks like...

myJson = [
  {
    ctrl: 'field1'
  },
  {
    ctrl: 'field2'
  }
];

We build our form by iterating the fields in the array:

this.myForm = this.fb.group({})

this.myJson.forEach(x => {
  this.myForm.addControl(x.ctrl, this.fb.control(''));
});

Then we can use the keyvalue pipe provided by angular to iterate the form controls and pass the form control with ctrl.key

<form [formGroup]="myForm">
  <div *ngFor="let ctrl of myForm.controls | keyvalue">
    <my-field [formControlName]="ctrl.key"></my-field>
  </div>
</form>

Another option, is to skip the component, and go fully for a dynamic form: https://angular.io/guide/dynamic-form

This should get you started, hopefully it helps! :)

Upvotes: 1

Related Questions