Failing to access template variable inside mat-sidenav-content

53 views Asked by At

I am trying to toggle a css class by accessing a div with a template variable inside mat-sidenav-content. I tried with both a @ViewChild and @ContentChild but none of them is being able to return the reference of the said div at runtime. Below is the simplified code.

<mat-sidenav-container>
    <mat-sidenav opened="true" mode="side" #sidenav>
      <-- navigation content here -->
    </mat-sidenav>
    <mat-sidenav-content class="content-wrapper">
      <div class="test" #myDiv>test</div>
        <router-outlet></router-outlet>
    </mat-sidenav-content>
</mat-sidenav-container>

Here is my controller class:

export class MenuControllerComponent
  implements AfterContentInit, AfterViewInit
{

  @ViewChild('myDiv') myChildDiv!: any;
  @ContentChild('myDiv', { static: false }) myContentDiv: any;

  constructor(
    private responsive: BreakpointObserver,
    private navigationService: NavigationService
  ) {}

  ngAfterViewInit(): void {
    console.log(this.myChildDiv); // logs undefined
  }

  ngAfterContentInit(): void {
    console.log(this.myContentDiv); // logs undefined
  }
}
1

There are 1 answers

0
boolean_values On

Possible answer: Check for any rendering logic you have written like *ngIf. If *ngIf delays the rendering, then you will get undefined

Right now the code looks fine. It would be ideal if you can provide this example in Stackblitz