Topic: Hamburger menu API: this.navbar is undefined

natenoctel free asked 3 years ago


According to the hamburger navbar api methods section at the bottom https://mdbootstrap.com/docs/angular/navigation/hamburger-menu/#docsTabsAPI

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 3 years ago

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


natenoctel free commented 3 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 3 years ago

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


natenoctel free commented 3 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.

FREE CONSULTATION

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

Status

Opened

Specification of the issue

  • ForumUser: Free
  • Premium support: No
  • Technology: MDB Angular
  • MDB Version: 9.3.1
  • Device: Desktop
  • Browser: Chrome
  • OS: OSX
  • Provided sample code: Yes
  • Provided link: Yes