Search code examples
angular-materialangular-material2angular-material-5angular-material-6

matAutocomplete control.registerOnChange is not a function


Can't find the issue.. It works but presents error and opens values after a bit of scroll.. Anyone?

control.registerOnChange is not a function

searchPort: FormControl = new FormControl();
searchPortResult = [];
...


this.searchPort.valueChanges.pipe(
    debounceTime(400))
  .subscribe(data => {
    this.codeTableSrv.searchport(data)
      .subscribe(response => this.searchPortResult = response);
  });

updatePortCode(event: MatAutocompleteSelectedEvent) {
  if (event.option.value !== undefined) {
    this.form.patchValue({
      portCode: {
        id: event.option.value.id,
        code: event.option.value.code,
        description: event.option.value.description,
        region: event.option.value.region
      }
    });
  }
}

displayPortFn(item) {
  if (item == null) {
    return '';
  }
  return item.code + ' ' + item.description;
}


createForm() {
    this.form = this.fb.group({     
      portCode: this.fb.group({
        id: ['', Validators.required],
        code: ['', Validators.required],
        description: ['', Validators.required],
        region: ['', Validators.required],
      }),    
    });
  }
<div class="col-6">
  <mat-form-field class="example-full-width">
    <input type="text" 
    placeholder="Search port" 
    aria-label="Number" 
    matInput 
    formControlName="portCode" 
    [formControl]="searchPort" 
    [matAutocomplete]="auto">
    <mat-autocomplete 
    #auto="matAutocomplete" 
    (optionSelected)="updatePortCode($event)" 
    [displayWith]="displayPortFn">
      <mat-option 
      *ngFor="let item of searchPortResult" 
      [value]="item">
        {{ item.code + ' ' + item.description }}
      </mat-option>
    </mat-autocomplete>
  </mat-form-field>
</div>

Need an example of how to change my code to make it work without the warning . the code is operational other than the stated error. it doesn't holt the process and enables yet to get autocomplete values as needed.


Solution

  • You're setting FormControl twice via formControlName and formControl. searchPort overrides portCode from your form. Since your code works fine you can just remove formControlName attribute.

    <div class="col-6">
      <mat-form-field class="example-full-width">
        <input type="text" 
        placeholder="Search port" 
        aria-label="Number" 
        matInput
        [formControl]="searchPort" 
        [matAutocomplete]="auto">
        <mat-autocomplete 
        #auto="matAutocomplete" 
        (optionSelected)="updatePortCode($event)" 
        [displayWith]="displayPortFn">
          <mat-option 
          *ngFor="let item of searchPortResult" 
          [value]="item">
            {{ item.code + ' ' + item.description }}
          </mat-option>
        </mat-autocomplete>
      </mat-form-field>
    </div>
    

    Stackblitz example