Dirk
Dirk

Reputation: 165

Undefined error Angular 2 class

I don't know why I get a undefined error. This is the error message I get: "TypeError: Cannot set property 'state' of undefined"

This is my code:

export class MobileMenuComponent implements OnInit {

menu: any;

constructor() { 


}

ngOnInit() { 

    this.menu.state = 'inactive';

    this.menu.togglemenu = function() {

        if (this.menu.state === 'inactive'){

            this.menu.state = 'active';

        }

        else {

            this.menu.state = 'inactive';

        }

    }

}


}

Upvotes: 0

Views: 1196

Answers (2)

Oleg Imanilov
Oleg Imanilov

Reputation: 2751

this inside togglemenu function - is for function itself, it doesn't contain menu member. You should use upper this inside function. Like this:

var that = this;
this.menu.togglemenu = function() {
   if (that.menu.state === 'inactive'){
            that.menu.state = 'active';
       }
        else {
            that.menu.state = 'inactive';
        }
    }

Upvotes: 1

Norbert Huurnink
Norbert Huurnink

Reputation: 1316

Define this.menu as empty object in your constructor and it will work.

Upvotes: 1

Related Questions