Search code examples
angularangular2-services

ExpressionChangedAfterIsHasBeenCheckedError because of updating my dropdownlist in angular 2


As the title says I'm getting an ExpressionChangedAfterIsHasBeenCheckedError and after reading this article, from what I understand it is a cautionary put in place to prevent inconsistencies. Exactly those words. So at some point I'm probably violating the unidirectional flow (I assume). What I have:

A dropdown box.

<select id="product" [(ngModel)]="model.searchParameters.productId">
 <option *ngFor="let product of products [value]="product.id">{{product.name}}</option>
</select>

An input box which triggers checkIban.

<div *ngIf="checkIban(productnumber, searchForm)">
   //show validation errors
</div>



checkIban(field: any, form: any): Boolean {
    if(field.dirty)
    {
        if(field.viewModel.length === Productnumber.Iban )
        {
           this.model.searchParameters.productId = Product.Ibannumber;
        }
    }
}

I'd like to think I understand the concept of the ExpressionChangedAfterIsHasBeenCheckedError, unfortunately for me, not well enough to truly apply a proper solution to this problem.

Using setTimeout is not an option (I've tried) as it creates an unpredictable state (as was written in the article). So can someone give me some pointers as to what I'm doing wrong?


Solution

  • I have decided to add ChangeDetectionStrategy in my solution.

    My component now looks like this.

    @Component{{
    selector: 'search',
    templateUrl:'./app/search/search.component.html',
    changeDetection:ChangeDetectionStrategy.OnPush, 
    providers:[SearchService]
    })
    

    After lots of reading on the subject I came across this solution. That seems to have done the trick.