Search code examples
angularcloneangular-reactive-forms

Angular 2 - Dynamic component template - how to clone a FormControl on demand


I implemented a dynamic data table, so far so good,

at the bottom of the table, there is a row containing inputs for some columns that allow the user to add a new record, and each added row is editable

my issue is that when I inline edit a row, I need the same validation, so I need to clone the FormControl I defined for the bottom row

here is an example of a definition I use in my code, when I instanciate my data table component (for one column)

...,
{
  name: this.getTrad('Points'),
  value: 'points',
  width: 100,
  type: DataTableComponent.INPUT,
  editable:true,
  numeric:true,
  validationControl:
    new FormControl({ value: '', disabled: false },
      [Validators.required,
      Validators.minLength(1), 
      Validators.maxLength(100)
    ])
},

so, how could I clone the FormControl to assign it to a dynamicaly created input ? I checked a FormControl instance, there is no accessor for the validators ?

so far the only idea I have is to give to my component an array of validators for each column instead of a whole instance of FormControl

if anyone has a better idea....

thanks


Solution

  • I just came across this question. I solved the following use case with a normal new instance:

    @Component({...})
    export class FooDialogComponent {
      formControl: FormControl;
    
      constructor(@Inject(MAT_DIALOG_DATA) public data: { system: number, control: AbstractControl }, // TODO define interface
                 public dialogRef: MatDialogRef<UpdateQuantityDialogComponent>) 
      {
        this.formControl = new FormControl(this.data.control.value, this.data.control.validator);
      }
    }
    

    With this approach, formControl has the same state and validators than the injected AbstractControl.

    Ofc, in case that the value of the control isnt a primitive type, youll need to perform a (deep)copy.

    Hope it helps