Difficulty in retrieving template variable within mat-sidenav-content

I am attempting to change a css class by targeting a div with a template variable within mat-sidenav-content. I have tried using both @ViewChild and @ContentChild but neither of them is able to retrieve the reference of the specified div at runtime. Below you will find the simplified code snippet.

<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>

Below is the code snippet from 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
  }
}

Answer №1

One way to solve this issue: Make sure to review any conditional rendering logic such as the use of *ngIf. If *ngIf is causing a delay in rendering, it may result in returning undefined values.

At the moment, the code appears to be in good shape. It would be beneficial if you could showcase this scenario in a Stackblitz example for further clarification.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Stop any ongoing search requests in Angular 7 using Ng2SmartTable

My current setup involves Angular version 7.0.1 and ng2-smart-table version 1.4.0. The issue I'm facing is that each search within the table triggers a new API request to fetch data. What I actually want is for only the latest search request to be pro ...

How can you display or list the props of a React component alongside its documentation on the same page using TypeDoc?

/** * Definition of properties for the Component */ export interface ComponentProps { /** * Name of something */ name: string, /** * Action that occurs when component is clicked */ onClick: () => void } /** * @category Componen ...

Tips for automatically setting a default radio button selection in Angular 8

I am a beginner in Angular 8 and I am struggling with setting one of the radio buttons to be checked by default. I have attempted adding attributes like [checked]="true", checked but the issue persists. HTML <div class="form-check"> <mat-ra ...

Utilizing Angular2 (Frontend) and Spring Boot (Backend) for Excel file uploading

As someone who is new to Angular 2, I am currently attempting to upload an Excel file from the Angular 2 frontend. My goal is to upload the Excel file from the Angular 2 frontend, send it to the Spring Boot backend for necessary modifications, and th ...

Update the names of the output fields within the returned object from the API

Recently I delved into nodejs and typescript to create an API using express. I attempted to return a custom object in my API structured as follows: export class Auction { private _currentPrice:number = 0; private _auctionName:string; public ...

What sets Angular 2/4 apart is the synchronous nature of Reactive forms, contrasting with the asynchronous behavior of template-driven forms

While looking through the documentation on angular.io, specifically about reactive forms being synchronous (Reactive forms are synchronous), I found myself struggling to grasp the concept of how reactive forms differ from template-driven forms in terms of ...

Encountering a blank page and slow loading when launching the VSCode debugger using VS Code version 1.76.1 and Chrome 111

Recently, I've encountered a problem with the VS Code debugger while trying to debug an Angular application. I created a new Angular app using the ng new command and made some changes to the ngOnInit function. When attempting to start the Chrome deb ...

Angular JSON Format Output: A Comprehensive Overview

I have noticed that the JSON output format currently being used may lead to errors in the application. I am trying to figure out how to achieve a different format for my code below. While I can see my data, the objects are not nested under the topics as ex ...

Angular 2.0 encountered an unexpected value from the module 'AppModule' which appears to be an '[object Object]'

Every time I attempt to load my angular version 2.0 application, I encounter the following error: (index):21 Error: Error: Unexpected value '[object Object]' imported by the module 'AppModule' import { ModuleWithProviders } from ' ...

When using EcmaScript imports with the 'node16' or 'nodenext' module resolution, it is important to include explicit file extensions in relative import paths. For example, did you intend to use './*.js'?

Within my package.json file, I have set "type": "module" and utilize SWC for compiling TypeScript code. For imports, I utilize import Example from './example'. In addition, I use the following script: "start": " ...

Struggle with typescript integration with emotion and styled components

Issue Description: I encountered an issue while working with typescript and emotion/styled libraries. When attempting to specify the type of the parent component that wraps a styled component, I faced difficulties. The scenario involves a parent componen ...

In this guide, we will explore the process of designing unique styles for ng

What is the proper way to customize CSS for a specific element? &.ng-select-focused { &:not(.ng-select-opened) > .ng-select-container { border-color: $ng-select-highlight; box-shadow: $ng-select-box-shadow; } } The offi ...

Waiting for the response from $http in Angular2

In almost all REST requests, I require the user's ID to be included. After logging in a user, I store the token in local storage and pass the ID to user.service.ts (using the function setUserId(userId);). However, when authenticating a user using onl ...

To enable the "Select All" functionality in ag-grid's infinite scrolling feature in Angular 4, utilize the header check box

Is there a way to add a checkbox in the header of ag-grid for selecting all options when using an infinite row model? It seems that the headerCheckboxSelection=true feature is not supported in this model. Are there any alternative methods to include a che ...

What is the best way to store an audio Blob in the repository file system?

Currently, I have set up a system to record user audio through the device's microphone and can successfully download it on the same device. However, my goal now is to store this audio in my database by making an API call. How can I efficiently send th ...

Leverage the power of TypeScript with knockout's pureComputed function

I am facing an issue with referencing the this object in a function called problem: const c = { f() { console.log("hi"); }, problem: ko.pureComputed(() => { return this.f(); }), }; [ts] The containing arrow function captures the glob ...

Issue with displaying international characters when using HttpClient's http.get() function in Angular.The

I am facing an issue that I can't quite figure out as I am new to Angular. My goal is to read a local .csv file and display its contents in a table. Everything seems to be working fine, except for the fact that when special characters like "č, ć, š ...

What are the reasons behind the restriction on using non-public members in TypeScript classes?

Consider the following scenario: class Trait { publicMethod() { this.privateMethod(); // do something more } private privateMethod() { // perform a useful action } } When attempting to implement it like this: cla ...

What is the correct way to add type annotations to an Axios request?

I have meticulously added type annotations to all endpoints in my API using the openapi-typescript package. Now, I am looking to apply these annotations to my Axios requests as well. Here is a snippet of code from a Vue.js project I have been developing: ...

Utilizing asynchronous JavaScript imports within exported classes

Currently, I have a package with async/dynamic exports that I import in the following manner: (async function() { const libEd = await import("../../.cache/ed25519wars/index.js"); })(); I plan to re-expose certain functions from libEd within a class str ...