Angular ReactiveForms

0

Hello, I'm trying to create a reusable form component using ReactiveForms. Like when I want to use a form, I'll just pass an array of my inputs from that form.

But I doubt if this is really possible. In my case I caught 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 do not know how to enter into my input array to create formbuilder controls! I wonder if this is really possible ?? Thank you in advance.

    
asked by anonymous 03.06.2018 / 01:59

1 answer

1

Imagining that your InputModels have a value property and a formControlName I would do so using the reduce function of the array:

  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);           
    }
    
04.06.2018 / 10:33