Reactiveforms Angular

Asked

Viewed 53 times

0

Hello, I am trying to create a reusable form Component using Reactiveforms. Like when I want to use a form, I will just pass an array of my inputs from that form.

But I’m not sure if it’s really possible. In my case I’m stuck here:

export class FormularioShared implements OnInit{
 
 formulario: FormGroup;
 @Input() inputs: InputsModels[];
 
 constructor(private formBuilder: FormBuilder){}
 ngOnInit(){
 this.formulario = this.formBuilder.group({
 [this.inputs[0].formControlName]: this.formBuilder.control('', Validators.required),
 });
 }
}

When I don’t know how to fill in my input array to create the formbuilder Controls! Would you like to know if this is really possible?? Thank you in advance.

1 answer

1


Imagining that your Inputmodels has a value property and a formControlName I would do so using the array’s reduce function:

  public construirForm(inputs: InputModels[]) {
        const formMap = inputs.reduce((dataAgg, iterator) => {
            const fmctrl =<AbstractControl> new FormControl(iterator.value);
            dataAgg[iterator.formControlName] =  fmctrl;     
            return dataAgg;
        }, {});
        return new FormGroup(formMap);           
    }
  • It worked that way, but in that way, how could the Validators?

  • const fmctrl =<Abstractcontrol> new Formcontrol(iterator.value, Validators.required);

  • or const fmctrl =<Abstractcontrol> new Formcontrol(iterator.value, iterator.validators);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.