0

I am having an issue accessing a child element with Angular 6 material application. I have a header component that has two child components, app-header and app-sidenav. The header.component.html has the following code:

<div style="height: 100vh">
  <app-tool-bar></app-tool-bar>
  <app-sidenav></app-sidenav>
</div>

In my app-tool-bar I have something like this:

<button (click)="sidenav.toggle()">
  <mat-icon>menu</mat-icon>
</button>

This button is supposed to toggle the sidenav menu (slide in and out) that is located in the app-side-nav component:

<mat-sidenav #sidenav>
    <mat-nav-list>
        ...
    </mat-nav-list>
</mat-sidenav>

I am having trouble achieving this functionality. I believe it has something to do with my header.component.ts file and the ViewChild decorator. I do somethig like this:

import { Component, ViewChild } from '@angular/core';
import { SidenavComponent } from './sidenav/sidenav.component';

...

@ViewChild(SidenavComponent) sidenav: SidenavComponent;

However, this keeps giving me undefined. I am hoping someone can guide me into the right direction into fixing this.

Thank you.

realnsleo
  • 709
  • 2
  • 12
  • 29

1 Answers1

-1

you can't access viewchildren in the oninit hook or in the constructor. it needs to be in the AfterViewInit hook or later. It also only queries the dom once, so if there's any ngIf statement that shows or hides it, this will always be undefined.

bryan60
  • 28,215
  • 4
  • 48
  • 65