Hamburger menu API: this.navbar is undefined

Topic: Hamburger menu API: this.navbar is undefined

natenoctel asked 2 years ago

According to the hamburger navbar api methods section at the bottom

When you add #navbar to your html component like this: <mdb-navbar #navbar></mdb-navbar>

and @ViewChild('navbar', { static: true }) navbar: NavbarComponent to your ts file, while also importing viewchild, and navbarcomponent

you should get access to MdbNavbar methods.

When I hover over the method in my code this.navbar.toggle() I can see that the method is valid, and exists on the component, so the import of the component is correct. However when I use the method in practice I get this error:

ERROR TypeError: Cannot read property 'toggle' of undefined

If I console log the value this.navbar I can see that it is undefined.

The template reference is there, but regardless it comes back as undefined.

Any ideas why this might be the case?

Arkadiusz Idzikowski staff commented 2 years ago

When exactly did you try to use this method? this.navbar should be available in the ngAfterViewInit hook.

natenoctel commented 2 years ago

I tried to use it in a function triggered by click event on a navbar item so if it was available in ngAfterViewInit it would have been available in the click event as ngAfterViewInit comes before in lifecycle.

Arkadiusz Idzikowski staff commented 2 years ago

Could you provide the HTML/ts code on which we will be able to reproduce that?

natenoctel commented 2 years ago

Unfortunately I don't have that code anymore, it wasn't working so I had to go with a different approach.

But it was as I described- the method was available in the ts file, but when the method was called the variable this.navbar was undefined.

I have had this same problem in trying to access other component's methods such as the tab and pills component.

I followed instructions exactly how they are detailed in the documentation for the API adding: the #navbar to my navbar component like: <mdb-navbar #navbar></mdb-navbar>

using the @ViewChild decorator by adding @ViewChild('navbar', { static: true }) navbar: NavbarComponent (and imported ViewChild and NavbarComponent from their appropriate locations.

and then using a function such as toggleMenu(){ this.navbar.toggle()} to trigger in a click event like (click)="toggleMenu()"

I'm wondering if there is something missing from the documentation about accessing methods in general, as this.navbar shoudn't come back undefined

Please insert min. 20 characters.


Hire our experts to build a dedicated project. We'll analyze your business requirements, for free.



Specification of the issue
  • User: Free
  • Premium support: No
  • Technology: MDB Angular
  • MDB Version: 9.3.1
  • Device: Desktop
  • Browser: Chrome
  • OS: OSX
  • Provided sample code: No
  • Provided link: Yes