@Viewchild doesn't have access to matSort

In my Angular project, I am having trouble getting my @ViewChild instance to work with MatSort in HTML.

component.ts file:

import { MatSort } from '@angular/material';

export class MyComponent {
     @ViewChild(MatSort) sort: MatSort;

}

ngOnInit() {
    console.log(this.sort); // returns undefined
}

component.html file:

<mat-table #table [dataSource]="dataSource" matSort>
           .......................................................
           .......................................................

</mat-table>

The issue I'm facing is that the sortChange property of matSort always returns as undefined.

Answer №1

The instance will be initialized and accessible in the AfterViewInit lifecycle hook:

export class MyClassComponent implements AfterViewInit {
  @ViewChild(MatSort) sort: MatSort;

  ngAfterViewInit() {
    console.log(this.sort); // MatSort{}
  }
}

For more information on Angular's lifecycle hooks, visit: https://angular.io/guide/lifecycle-hooks.

Answer №2

If you have already included the following imports at the class level:

import { MatSort, MatTableDataSource } from '@angular/material';

This grants access to the types MatSort and MatTableDataSource within your .ts class. However, if you also want to utilize these modules as directives in your component's .html file, you need to import them in your app.module.ts. One way to do this is by creating a separate NgModule that consolidates all of the material components you are using.

For example, create a module called material\material.module.ts:

import { NgModule } from '@angular/core';

import {
  MatTableModule,
  MatSortModule, 
} from '@angular/material';

@NgModule({
  imports: [
      MatTableModule,
      MatSortModule, 
    ],
  exports: [
      MatTableModule,
      MatSortModule, 
    ]
})
export class MaterialModule { }

Then, in your app.module.ts, include the MaterialModule alongside other necessary imports:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { HttpClientModule } from '@angular/common/http';

import { MaterialModule } from './material/material.module';
import { AppComponent } from './app.component';
import { MyComponent } from './my/my.component';

@NgModule({
  declarations: [
    AppComponent,
    MyComponent
  ],
  imports: [
    BrowserModule,
    MaterialModule,
    BrowserAnimationsModule,
    HttpClientModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Answer №3

Dealing with angular 7, I encountered a problem that was resolved by including MatSortModule in the app.modules.ts file. The error I faced is similar to the one described in this helpful resource. Interestingly, there were no clear indications pointing to the absence of MatSortModule.

Read more about the original solution: Angular 5 - Missing MatSortModule

Answer №4

When working in Angular 8, I encountered a situation where I needed to utilize a setter along with an optional parameter static=false:

   @ViewChild(MatSort, {static: false})
   set sort(sort: MatSort) {
      this.sortiments.sort = sort;
      this.selectedSortiments.sort = sort;
   }

I came across the solution here: https://github.com/angular/components/issues/15008#issuecomment-516386055

Answer №5

  1. Ensure to include the line of code
    @ViewChild(MatSort,{static:false}) sort: MatSort;
  2. Double check that there are no occurrences of *ngIf in your table template

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

Include a hash in the URL when the current location is entered into the view by scrolling

In my current situation, I am required to implement a @HostListener in order to navigate to an element within my web page: @HostListener('click', ['$event']) onClick(e: any) { e.preventDefault(); const href = e.target.getAttri ...

What is the best way to emphasize specific months and years in an Angular Material datepicker?

I have an array of days, which can be from any year. I am attempting to customize the Angular Material datepicker to highlight specific months and years in the selection views based on the array of days. .html <input [matDatepicker]="picker" ...

Error Encountered During Angular 2 Protractor End-to-End Testing Runtime

Whenever I try to run protractor, I encounter this error message: [15:47:46] E/launcher - Error: TSError: ? Unable to compile TypeScript Conflicting library definitions for 'selenium-webdriver' found at 'G:/WebServers/home/smsc/SMSC2/module ...

Error: The function being called in <class> is not recognized as a function

I have a unique situation with my component setup export class Component1Component implements OnInit { public greetings: string =""; constructor(private greeter: Greeter) { } ngOnInit() { this.greetings = this.greeter.sayHello(); } } The structur ...

Comparing JSON objects with JavaScript models: A guide

Currently I'm working with angular 2 and I have an array of data. data: MyModel[] = [ { id: 1, name: 'Name', secondName: 'SecondName' } In addition, I have created the interface MyModel: interface MyModel { id: number, nam ...

Typescript-powered React component for controlling flow in applications

Utilizing a Control flow component in React allows for rendering based on conditions: The component will display its children if the condition evaluates to true, If the condition is false, it will render null or a specified fallback element. Description ...

Tips for obtaining the Component instance from the ViewContainerRef.get() method for dynamically created components

Explanation of my current goal successfully add components to a ViewContainerRef (completed) initialize these dynamic components with properties (done) gain access to the dynamically created Component instances for decision-making purposes. The issue at ...

The canDeactivate function in the Angular 2 router can modify the router state even if I choose to cancel an action in the confirmation popup

In my Angular 2 project, I have implemented the canDeactivate method to prevent browser navigation. When a user tries to leave the page, a confirmation popup is displayed. However, if the user chooses to cancel, the router still changes its state even th ...

Trouble with Excel Office Script setInterval functionality

Trying to automatically recalculate an Excel worksheet every second using Office Script. Unfortunately, my initial approach did not succeed. function sendUpdate(sheet: ExcelScript.Worksheet) { console.log('hi'); sheet.calculate(true); } func ...

I am seeking a method to display formatted document texts from a file located in the asset folder within an Angular HTML document as a pop-up

Text File Content -> <b>Test</b> Below is a snippet of Angular HTML I attempted: <embed src=".\assets\docs\about\BRANCH_MASTER.txt">--> <object data=".\assets\docs&bs ...

Experimenting with directive using jasmine

I've been working on this directive but I'm having trouble writing the jasmine test for it. Any suggestions? import { Directive, Output, EventEmitter, HostListener } from '@angular/core'; @Directive({ selector: '[ctrlKeys]&apos ...

Ways to deactivate selecting rows in a datatable

Is there a way to deactivate the select feature specifically within datatables? An example of using ctrl+a for disabling select all function is available here https://i.stack.imgur.com/RQNXT.png ...

Styling does not affect an Angular component that is injected into an iframe

I am facing an issue with styling in an iframe when trying to append my own angular component. Despite various attempts, I have been unsuccessful in getting the styling to apply to the component within the iframe. Upon loading the iframe, I use JavaScript ...

Avoiding redundant EventEmitters when transferring @Output to a child component

While working on a form component, I decided to separate the form action buttons into a child component. This led me to create two EventEmitter and handlers for the same action. I'm wondering if there is a way to directly pass the 'onDiscard&apo ...

Converting an array into an object using Typescript and Angular

I have a service that connects to a backend API and receives data in the form of comma-separated lines of text. These lines represent attributes in a TypeScript class I've defined called TopTalker: export class TopTalker { constructor( pu ...

What is the process for running an npm package command on a specific subdirectory using PowerShell?

Is there a way to run an npm package command on a specific subdirectory using PowerShell? My situation involves having an ng2 application embedded within a .NET MVC app. The ng2 directory is nested within the main root directory structured as MySite/ng2. ...

Is there a method to automatically select or deselect a checkbox based on the incoming value in Angular?

When new data comes in, the table gets populated and I can't specify that "A" should be checked while "D" shouldn't. re(ref: getrefactormodel, count:number){ let data= this.fb.group({ word_to_rename: [ref.word_to_rename, Vali ...

Tips for detecting the end of a scroll view in a list view

I've encountered an issue with my scrollView that allows for infinite scrolling until the banner or container disappears. What I'm aiming for is to restrict scrolling once you reach the last section, like number 3, to prevent the name part from m ...

Tips for ensuring elements within a modal receive immediate focus when opened in Angular 2

I am relatively new to Angular JS and I am encountering some challenges with implementing a directive in Angular 2 that can manage focusing on the modal when it is opened by clicking a button. There have been similar queries in the past, with solutions pr ...

Implement new functionalities within JDL Jhipster for an Angular project

For instance, I am interested in incorporating functions such as onChange, focusout, onBlur, onClick while passing an extra parameter in jdl like this: <input type="text" class="form-control" name="firstName" (onChange)= ...