What causes the “control.registerOnChange is not a function” error

后端 未结 10 1912
一向
一向 2020-12-01 20:39

I have a form using the reactive form approach. The form is created as follow in my pug:

form([formGroup]=\'form\', novalidate=\'\', (ngSubmit)=\'postSurvey(         


        
相关标签:
10条回答
  • 2020-12-01 21:08

    If have defined a FormArray field in your form, note that you do NOT need to label it with formControlName="". You need to handle the input and validation in other ways (setters, getters, functions), but will definitely get an error if you try to assign formControlName to a FormArray!

    0 讨论(0)
  • 2020-12-01 21:10

    Adding in what was causing it in my situation.

    .ts file,

    ...
    
    export class MyComponent {
      dateFrom = new FormControl(new Date());
    ...
    }
    

    .html file,

      <mat-form-field>
        <input matInput [matDatepicker]="dateFrom" [formControl]="dateFrom"
          placeholder="Min date">
        <mat-datepicker-toggle matSuffix [for]="dateFrom"></mat-datepicker-toggle>
        <mat-datepicker #dateFrom ></mat-datepicker>
      </mat-form-field>
    

    Basically, within the template file, it didn't know which 'dateFrom' to choose, and chooses the one in the template file, which isn't the FormControl in my typescript file, it's the mat-datepicker element in the template file.

    Renaming the FormControl to dateFromCtrl fixed this,

    i.e.

    ...
    
    export class MyComponent {
      dateFromCtrl = new FormControl(new Date());
    ...
    }
    

    .html file,

      <mat-form-field>
        <input matInput [matDatepicker]="dateFrom" [formControl]="dateFromCtrl"
          placeholder="Min date">
        <mat-datepicker-toggle matSuffix [for]="dateFrom"></mat-datepicker-toggle>
        <mat-datepicker #dateFrom ></mat-datepicker>
      </mat-form-field>
    

    Works as expected.

    Kodos to VS Code for figuring this out. I got pushed this direction by doing a Cmd + Click on the initial 'dateFrom' at [formControl]="dateFrom", and it pointed me to the mat-datepicker element.

    0 讨论(0)
  • 2020-12-01 21:17

    I have also encountered this error when mixing template driven with reactive driven approaches (by mistake):

    <input #inputCtrl
           [formControl]="inputCtrl"
    />
    

    inputCtrl was properly defined in the component. Of course, #inputCtrl must be scrapped in order to work (it was hard to see when input had about 10 attributes).

    0 讨论(0)
  • 2020-12-01 21:20

    This error also appears when we use a reactive form inside ng-template in conjunction with *ngIf.

    To avoid this use ng-container and do not use ngElse.

    0 讨论(0)
提交回复
热议问题