user11903678
user11903678

Reputation:

How to solve "Expression has changed after it was checked." when occuring because of the @Input variable update?

When the webpage container is scrolled I use eventemitters which send to the parent element the target. The parent page sends to another child - the menu- the targets so that the menu can activate / deactivate correspondingly the menu titles. The variables are sent and updated ok from the container to the parent but when sent further from parent to child (menu component) the error

ERROR Error: "ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'Home: undefined'. Current value: 'Home: true'."

Update parent:

<scroll-card (id_active) ="activate_id($event)"></scroll-card>

and the component

export class Parent implements OnInit {
    home:boolean;

    constructor() {}

    ngOnInit() {}

    activate_id(message: string){
        if(message == "Home"){
            this.home=true;
        }
    }
}

This is how I send the data to the child:

<menu [Home] ="home"></menu>

And this is how I receive the data:

import { Component, OnInit, Input, EventEmitter, SimpleChanges } from '@angular/core';

@Component({
    selector: 'menu',
    templateUrl: 'menu',
    styleUrls: ['./menu.component.scss']

    export class Menu implements OnInit {

    constructor() { }

    ngOnInit() {
    }

    @Input() Home;
}

Upvotes: 2

Views: 486

Answers (1)

noamyg
noamyg

Reputation: 3104

In order to really understand why this happens, you need to show how you emit a change to id_active. However, it is always possible to manually trigger change detection:

import { ChangeDetectorRef } from '@angular/core';

export class Parent implements OnInit {
    home:boolean;

    constructor(private cdRef:ChangeDetectorRef) {}

    ngOnInit() {}

    activate_id(message: string){
        if(message == "Home"){
            this.home=true;
            this.cdRef.detectChanges();
        }
    }
}

Upvotes: 1

Related Questions