Topic: Hamburger menu API: this.navbar is undefined
natenoctel
asked 8 months 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?
Open
- User: Free
- Premium support: No
- Technology: Angular
- MDB Version: 9.3.1
- Device: Desktop
- Browser: Chrome
- OS: OSX
- Provided sample code: No
- Provided link: Yes
Arkadiusz Idzikowski staff commented 8 months ago
When exactly did you try to use this method?
this.navbarshould be available in thengAfterViewInithook.natenoctel commented 8 months ago
I tried to use it in a function triggered by click event on a navbar item so if it was available in
ngAfterViewInitit would have been available in the click event asngAfterViewInitcomes before in lifecycle.Arkadiusz Idzikowski staff commented 8 months ago
Could you provide the HTML/ts code on which we will be able to reproduce that?
natenoctel commented 8 months 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
#navbarto my navbar component like:<mdb-navbar #navbar></mdb-navbar>using the
@ViewChilddecorator 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