0

I am using Angular autocomplete which I have connected to an API. Search results should not be returned until after typing has started. After typing a few letters in the box this error comes up in the console.

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'xxxx'. Current value: 'undefined'..

I have tried using change detection but that hasn't helped.

The main issue seems to be with the collectFieldValue function because, without it, when I console log the value, the value never becomes undefined.

Search.component.html

    <input type="text" class="searchItem" placeholder="Begin your’"
    aria-label="Begin your search" matInput [matAutocomplete]="auto" (ngModelChange)="inputCheck($event)" 
    [(ngModel)]="searchInput" (focusout)="onFocusOut()" (focus)="onFocus()"
    (keydown)="onKeyDown()" >

Search.component.ts

@Input() setSelectedLocation!: Function;

     inputCheck(value: any) {
        if (value !== undefined && value !== "" && value !== null) 
        {
          this.collectFieldValue(value, this.sharedService.sharedVal && this.sharedService.sharedVal !== "" ? this.sharedService.sharedVal : undefined)
        }
      }

Main.component.html

<app-search-box
    [collectFieldValue]="triggerLocationSearch"
    [setSelectedLocation]="setSelectedLocation">
</app-search-box>
A.Mac
  • 203
  • 3
  • 19

2 Answers2

0

ExpressionChangedAfterItHasBeenCheckedError usually happens when something in template changes before the entire template is rendered the first time. E.g some function in template changes template itself.

Wrap the suspected method in setTimeout to trigger this in next cycle. If that removes the error then you've found out the culprit.

Afterwards figure out why template change happens before it's rendered. Right not I can't spot the problem.

setTimeout(() => {
 this.collectFieldValue(value, this.sharedService.sharedVal && this.sharedService.sharedVal !== "" ? this.sharedService.sharedVal : undefined)
})
Joosep Parts
  • 5,372
  • 2
  • 8
  • 33
0

I was getting this error after modifying a Map object that was being iterated over using

*ngFor="let entry of myMap.entries()"

The fix that worked for me was adding ChangeDetectionStrategy.OnPush to my component declaration:

@Component({
  selector: 'component',
  templateUrl: 'component.html',
  changeDetection: ChangeDetectionStrategy.OnPush
})..
Ahmer Ali Ahsan
  • 5,636
  • 16
  • 44
  • 81