Aniruddha Das
Aniruddha Das

Reputation: 21688

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

I am writing a component which takes one @Input parameter and display it in the html bit I am getting below error.

SuggestionsComponent.html:54 ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'undefined'. Current value: '<p>so string value</p>
'.
    at viewDebugError (core.js:9801)
    at expressionChangedAfterItHasBeenCheckedError (core.js:9779)
    at checkBindingNoChanges (core.js:9948)
    at checkNoChangesNodeInline (core.js:14002)
    at checkNoChangesNode (core.js:13976)
    at debugCheckNoChangesNode (core.js:14805)
    at debugCheckDirectivesFn (core.js:14707)
    at Object.eval [as updateDirectives] (SuggestionsComponent.html:54)
    at Object.debugUpdateDirectives [as updateDirectives] (core.js:14689)
    at checkNoChangesView (core.js:13814)

Here is the component.

export class SuggestionsComponent implements OnInit, AfterViewInit {

  @Input() suggestions: Array<Suggestions>;
  @Output() approveSuggestion = new EventEmitter<Object>();

  constructor(
    private elementRef: ElementRef,
  ) {
  }

  ngOnInit() {
  }

  ngAfterViewInit() {
    if (this.suggestions && this.suggestions.length > 0) {
      this.suggestions
        .map((value, index) => {
          this.suggestions[index].newSuggestion = value.descriptionSuggestion;
        });
    }
  }

Upvotes: 0

Views: 3697

Answers (1)

Aniruddha Das
Aniruddha Das

Reputation: 21688

The problem is changing component @Input variable value in ngAfterViewInit(). At that time angular changes view and making some change in bind value in upsets angular.

So moving the @input() value to ngOnInit solves the problem as its the method which executes during component bootstrap.

  ngOnInit() {

    // This is placed here in the in after view init is because it will throw exception as view will be change at that time
    this.suggestions
      .map((value, index) => {
        this.suggestions[index].newSuggestion = value.descriptionSuggestion;
      });
  }

  ngAfterViewInit() {
    if (this.suggestions && this.suggestions.length > 0) {
      this.suggestions
        .map((value, index) => {
          this.elementRef.nativeElement.querySelector('.class' + index).style.display = 'none';
        });
    }
  }

Upvotes: 1

Related Questions