@ViewChild not getting initialized in ngOnInit lifecycle hook

I have encountered an issue with my two MatTables in separate components, each using data sources from different observables. One of the tables has a functioning sort feature, but the other seems to have a problem with the @ViewChild for MatSort not initializing during ngOnInit.

Even though the data renders and the table displays sort buttons, the sorting functionality is not working properly. I have checked my imports, module, and everything seems to be correct.
When logging the MatSort object, one component shows a valid MatSort object while the other shows it as undefined.

The sorting feature is not functioning correctly.

Code snippet from Feed.component:

   import { PostService } from './../../services/post.service';
   import { Post } from './../../models/post';
   import { Component, OnInit, ViewChild, ChangeDetectorRef} from 
     '@angular/core';
   import { MatSort, MatTableDataSource, MatCheckbox, MatPaginator, 
     MatTabChangeEvent, MatDialog, MatDialogActions, MatTable}  from 
   "@angular/material"



export class FeedComponent implements OnInit {
  @ViewChild(MatSort) sort: MatSort;
  @ViewChild(MatPaginator) paginator: MatPaginator;
  postData: Post[] =[];
  dataSource : MatTableDataSource<any> 
  currentUser = JSON.parse(localStorage.getItem('user'))
  displayedColumns:string[] = ['User','Title', "Description", 
  "Contact" ]
  posts = this.ps.getPosts();

  constructor(private ps: PostService, public dialog:MatDialog, 
    public change:ChangeDetectorRef, public ms:MessageService) { 

  }



refreshPosts(){
   console.log(this.sort) < -------comes back undefined
  this.posts.subscribe(posts=>{
    this.dataSource.sort = this.sort
     this.postData = posts.filter(post => post.uid != 
       `${this.currentUser.uid}` && post.claimedBy 
        !=`${this.currentUser.uid}`);
     this.dataSource= new MatTableDataSource(this.postData)
     this.dataSource.paginator = this.paginator;
    });

  }
ngOnInit() {
   this.refreshPosts()
   console.log(this.sort)
   }


Post.service
  getPosts(){
    return  this.afs.collection('posts').snapshotChanges()
     .pipe(map(actions => 
     actions.map(this.documentToDomainObject)))
  }
 documentToDomainObject = _ => {
  const object = _.payload.doc.data();
  object.id = _.payload.doc.id;
  return object;
}

In contrast, the next component initializes in a similar way, but the @ViewChild for MatSort shows up as a valid MatSort Object.

Code snippet from Message.component:

export class MessageComponent implements OnInit {

 @ViewChild(MatSort) sort: MatSort;
  userReceived: MatTableDataSource<any>;
  userSent: MatTableDataSource<any>;
  displayedColumns:string[] = ["createdAt",'author',"title", "Delete"]
  sentColumns:string[] = ["createdAt","recipient", "title", "Delete"]


  currentUserId= this.currentUser['uid']
  currentUsername = this.currentUser['displayName']
  recipient:any;
  selectedMessage: MatTableDataSource<Message>;
  messageColumns= ['From','Title',"Body"];

  constructor(public ms:MessageService, public change:ChangeDetectorRef, public dialog: MatDialog  ) { }

  ngOnInit() {
    console.log(this.sort)
    this.updateMessages()
    this.currentUserId = this.currentUserId;
    this.currentUsername = this.currentUsername;

 }

updateMessages(){
    this.ms.getUserSent().subscribe(messages => {
      console.log(this.sort) <------logs MatSort object
      this.userSent = new MatTableDataSource(messages)
      this.userSent.sort = this.sort
      console.log(this.userSent.sort)
      console.log(this.userSent.data)

    })

Code snippet from message.service:

 getUserSent() {
    let messages:any[] = [];
    this.userSent = this.afs
      .collection('messages', ref => ref.where('uid', '==', `${this.currentUser.uid}`)).snapshotChanges() 
return this.userSent
  }

Code snippet from feed.component.html:

<div class = "mat-elevation-z8">
    <mat-form-field>
        <input matInput (keyup)="applyFilter($event.target.value)" placeholder="Search Posts">
      </mat-form-field>
  <table matSort mat-table [dataSource]="dataSource" style="text-align:left">
      <ng-container matColumnDef="User">
          <th mat-header-cell *matHeaderCellDef mat-sort-header>User</th>
          <td mat-cell *matCellDef="let post">{{post.displayName}}</td>
       </ng-container>

  <ng-container matColumnDef="Title">
    <th mat-header-cell *matHeaderCellDef>Title</th>
    <td mat-cell *matCellDef="let post">{{post.title | truncate:15:false }}</td>
 </ng-container>

  <ng-container matColumnDef="Description">
    <th mat-header-cell *matHeaderCellDef >Description</th>
    <td mat-cell *matCellDef="let post">{{post.description | truncate: 20 : false}}</td>
  </ng-container>

  <ng-container matColumnDef="Contact">
    <th mat-header-cell *matHeaderCellDef> Contact </th>
    <td mat-cell *matCellDef="let post">
      <button  id="{{post.id}}" color="primary" (click)="openDialog($event.target.id)" style = "outline:none" value={{post.id}}>Claim</button>
    </td>

  </ng-container>

  <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
  <tr mat-row *matRowDef='let row; columns: displayedColumns'></tr>
</table>
</div>
  <mat-paginator [length]="this.postData.length" [pageSize]="5" [pageSizeOptions]="[5,10,25]"></mat-paginator>

I am struggling to understand why the sort property returns undefined in my first component while in the second working component it returns a proper object. Could someone shed light on whether there may be something related to the order of @ViewChild declaration?

Answer №1

According to the official documentation: https://angular.io/api/core/ViewChild#description

The view queries are set up before the ngAfterViewInit callback is executed.

To properly initialize the @ViewChild property, it must be called within the ngAfterViewInit lifecycle hook.

export class MessageComponent implements OnInit, AfterViewInit {

   @ViewChild(MatSort) sort: MatSort;

   ngAfterViewInit(){
      console.log(this.sort)
   }
}

If you're using Angular 8, you'll need to adjust the implementation of @ViewChild properties to include the static flag as a requirement.

Answer №2

One issue with the FeedComponent is that the assignment of this.dataSource.sort = this.sort is done before initializing this.dataSource.

refreshPosts(){
  console.log(this.sort) < -------returns undefined
  this.posts.subscribe(posts=>{
     this.postData = posts.filter(post => post.uid != `${this.currentUser.uid}` && post.claimedBy !=`${this.currentUser.uid}`);
     this.dataSource= new MatTableDataSource(this.postData)
     this.dataSource.sort = this.sort // assign after initializing this.dataSource
     this.dataSource.paginator = this.paginator;
    });
  }

It's important to note that console.log(this.sort) will still show undefined due to lifecycle sequences. During ngOnInit, view queries are not set.

This leads to the question of how the assignment this.dataSource.sort = this.sort works in ngOnInit of MessageComponent.

The answer, in simple terms, is that this code executes in a subscribe callback. The subscribe callback gets executed when the observable emits, which involves an asynchronous operation. This async operation occurs in a subsequent change detection cycle after the cycle where ngAfterViewInit hook runs.

You won't encounter undefined output in your second component because the console.log statement also operates within a subscribe callback. If you move that log statement outside of the subscribe callback, it will also display undefined.

If you place console.log statements in the ngAfterViewInit hook, they will always print actual values whether inside a subscribe callback or not.

To summarize;

Assign values after initializing this.datasource

this.dataSource= new MatTableDataSource(this.postData)
this.dataSource.sort = this.sort // assign after initializing 

And perform this action in the ngAfterViewInit hook, even though it may function in ngOnInit due to the asynchronous nature of the operation.

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

How can I refresh the information in the navbar in Angular2?

Looking for guidance on the following scenario: I am working with two distinct components called navbar and homepage. The navbar has a specific area designated for displaying the city name. Within the homepage component, there is a form that includes a ...

An error is encountered with the getToken function in the Edge Runtime when using dynamic code evaluation methods such as 'eval', 'new Function', or 'WebAssembly.compile'

Working on a project that utilizes NextAuth.JS for authentication and Redux-Saga as the state manager. To enable refresh token rotation, I have created the following set of functions: get-token.ts: import { UUID } from 'crypto'; import jwt from ...

The CSS variables set within the :root section of styles.scss are not recognized as valid

Trying to implement global colors using CSS variables in my Angular 11 app. The styles.scss file contains: :root{ --primary : #0b68e8; --secondary:#ABCFFF; } .test-class{ background: var(--primary); } However, when applying this class in one ...

When utilizing typescript to develop a node module and importing it as a dependency, an issue may arise with a Duplicate identifier error (TS2300)

After creating a project called data_model with essential classes, I built a comprehensive gulpfile.js. This file not only compiles .ts to .js but also generates a unified .d.ts file named data_model.d.ts, which exports symbols and is placed at the root of ...

Looking to retrieve parameters from a route in Angular 7's Router

Encountered an issue with the params in the router configuration. { path: 'profile', component: ProfileComponent, canActivate:[AuthGuard], children: [ { path: 'section/:id/:idarticle', component: WriteArticleCom ...

Updating the React State is dependent on the presence of a useless state variable in addition to the necessary state variable being set

In my current setup, the state is structured as follows: const [items, setItems] = useState([] as CartItemType[]); const [id, setId] = useState<number | undefined>(); The id variable seems unnecessary in this context and serves no purpose in my appl ...

Identifying digits and letters by processing individual user input

I am facing a coding challenge with the following code snippet: <div class="form-group"> <label for="txtName">Name</label> <input type="text" pInputText class="form-control" id="txtName" formControlName="name"> < ...

Whenever npm or ng-packagr are updated, the publishing process may attempt to use an incorrect package name or version

Following the transition to [email protected], [email protected], and Angular@13, I am encountering difficulties while attempting to publish a package generated by ng-packager to the npm repository. This is the content of the package.json file: ...

The sequence for initializing properties in Typescript

In my Typescript code, I have 2 classes named A and B. Class B inherits from class A, where class A's constructor calls a function called init, and class B overrides the init function. a.ts export default class A { constructor() { this.ini ...

The efficiency of React Context API's setters is remarkably sluggish

I have a goal to implement a functionality where the background gradient of a page changes depending on whether the child's sublinks are expanded or collapsed. To achieve this, I am using the useContext hook. However, I've noticed that although e ...

Display a custom error message containing a string in an Angular error alert

How can I extract a specific string from an error message? I'm trying to retrieve the phrase "Bad Request" from this particular error message "400 - Bad Request URL: put: Message: Http failure response for : 400 Bad Request Details: "Bad Request ...

Encountering a problem with updating values in local storage using ReactJS

My goal is to store values in local storage, but I am facing an issue where it saves an empty array in local storage the first time I click on Set Item. After the initial setup, the code works as expected. I am relatively new to React and TypeScript. Below ...

Incorporate additional fields into the info.plist file for a Cordova iOS application

I am in the process of developing a custom plugin that will automatically add entries to the info.plist file for an iOS application built with Cordova and Angular 4. One specific entry I need to include triggers the application to exit when the home button ...

How to make a GET request to a Node server using Angular

I am currently running a node server on port 8000 app.get('/historical/:days' ,(req,res,next){..}) My question is how to send a request from an Angular app (running on port 4200) in the browser to this node server. Below is my attempt: makeReq ...

The standard build.gradle settings for Ionic projects on Android

By default, in the platforms/android/build.gradle file, I have the following configuration: allprojects { repositories { google() jcenter() } //This replaces project.properties w.r.t. build settings project.ext { defa ...

What is the best way to expand upon the declaration file of another module?

I have encountered a problem with declaration files in my AdonisJS project. The IoC container in Adonis utilizes ES6 import loader hooks to resolve dependencies. For instance, when importing the User model, it would appear as follows: import User from ...

Verify the presence of identical items in the array

I have been attempting to identify any duplicate values within an array of objects and create a function in ES6 that will return true if duplicates are found. arrayOne = [{ agrregatedVal: "count", value: "Employee Full Name" }, { agrrega ...

What is the process for obtaining the complete URL using the getDownloadURL() function along with a token?

An error occurred due to an unresolved FirebaseStorageError: "storage/object-not-found". The message indicates that the object 'k91a73uzb99' does not exist in Firebase Storage. This type of error is categorized under FirebaseError with a code of ...

The dynamic key for an object is not being inferred by Typescript

In my Redux action, I have a simple setup: export interface UpdateUserSettingsPayloadType { videoInput?: MediaDeviceInfo; audioInput?: MediaDeviceInfo; audioOutput?: MediaDeviceInfo; } export const updateUserSettings = ( payload: UpdateUserSetting ...

Angular - Turn off date selection in datepicker when toggle switch is activated

I am currently utilizing angular material and I need to figure out how to deactivate the datepicker after toggling a slide. Below is my upload form equipped with a datepicker: <form #uploadForm="ngForm" (keydown.enter)="$event.preventDefault()" (ngSub ...