简体   繁体   中英

(Angular 11) TypeError: control.registerOnChange is not a function

i need the values in a dynamic form but always show me this error "ERROR Error: control.registerOnChange is not a function"

i build my form like this:

referential.values.forEach(referentialValue => {
    const newFormGroup = new FormGroup({
      value: new FormControl(referentialValue.value),
      libelle: new FormControl(referentialValue.libelle),
      primaryColor: new FormControl(referentialValue.primaryColor),
      secondaryColor: new FormControl(referentialValue.secondaryColor),
      borderColor: new FormControl(referentialValue.borderColor),
      default: new FormControl('')
    });
    this.referentialArray.push(newFormGroup);
  });
this.form = new FormGroup({
  referentials: this.referentialArray
});
this.form.disable();

and the html (not whole):

  <tbody formArrayName="referentials">
    <tr *ngFor="let referential of referentialArray.controls; let i = index">
      <td><input type="text"
          [formControlName]="i"></td>
      <td><input type="text"
          [formControlName]="i"></td>

any ideas?

You are close, change formControlName to formGroupName in you referential loop.

It will look something like this:

<form [formGroup]="myForm" (ngSubmit)="submit(myForm.value)">
  <div formArrayName="referentials">
    <div *ngFor="let child of myForm.get('referentials').controls; let i = index">
      <div [formGroupName]="i">
        <label>{{i+1}}. Label: </label>
        <input formControlName="label" /><br>
        <label>{{i+1}}. Value: </label>
        <input formControlName="value" />
      </div>
      <br>
    </div>
  </div>
  <button type="submit">Submit</button>
</form>

Working example on stackblitz

I take that this.referentialArray is a simple array

this.form = new FormGroup({
  referentials: this.referentialArray
});

can you try something like following?

this.form = new FormGroup({
  referentials: new FormArray([])
});

var refFormArray = this.form.get('referentials') as FormArray;
referential.values.forEach(referentialValue => {
    const newFormGroup = new FormGroup({
      value: new FormControl(referentialValue.value),
      libelle: new FormControl(referentialValue.libelle),
      primaryColor: new FormControl(referentialValue.primaryColor),
      secondaryColor: new FormControl(referentialValue.secondaryColor),
      borderColor: new FormControl(referentialValue.borderColor),
      default: new FormControl('')
    });

    refFormArray.push(newFormGroup);
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM