Guide on developing a personalized directive for mat select element and capturing the change event

In my current project, the use of ElementRef's nativeelement.value is essential due to some persistent readonly errors happening only in my custom directive.

export class DeliveryAcrossDirective {
  @Input('key') key: string;
  @Input('component') component: string;
  constructor(
    private store: Store,
    private elementRef: ElementRef<HTMLInputElement>
  ) {
    this.key = '';
    this.component = '';
  }
  @HostListener('change') onChange() {
    console.log('noticed something');

    this.store.dispatch<IAction<IAdjust>>({
        type: RDX_DELIVERY_ACROSS_ADJUST,
        payload: {
          key: this.key,
          value: this.elementRef.nativeElement.value
        },
        component: this.component
      })
  }

}

However, I have encountered a problem where my directive does not capture the change event from a mat select.

<mat-form-field class="full-width" [@transformRightLeftStateTrigger]="stateDown | async">
  <mat-label>
    {{ country | async }}
  </mat-label>
  <mat-select [formControl]="countryFormControl"
  appDeliveryAcross
  [key]="'iso'"
  [component]="'delivery-across'" >
    <mat-option *ngFor="let language of (languages | async)"  [value]="language.value">
      {{ language.country }}
    </mat-option>
  </mat-select>
</mat-form-field>

On the contrary, classic inputs work perfectly fine with capturing the change event as shown below:

        <mat-form-field class="full-width" [@transformRightLeftStateTrigger]="stateDown | async">
          <input matInput
          [formControl]="minFormControl"
          [errorStateMatcher]="errorStateMatcher"
          placeholder="Minimaal"
          appDeliveryAcross
          [key]="'min'"
          [component]="'delivery-across'"
          type="number">
        </mat-form-field>

If anyone has insights on how to successfully capture the change event from a mat select using a directive, please share your knowledge!

Answer №1

It is essential to pay attention to the selectionChange event

@Directive({
    selector: '[appMyCustomDirective]',
})
export class MyCustomDirective {
    constructor() {}

    @HostListener('selectionChange', ['$event'])
    onChangeSelection(event: MatSelectChange): void {
        console.log(event);
    }
}

Answer №2

It's uncertain which specific version of Angular Material you are utilizing, but it is likely that the change event simply does not exist for the mat-select. More information can be found at

You may need to make modifications to your directive for mat-selects

Answer №3

If you want to monitor changes in a mat-select element, there's no need to use the HostListener decorator. Simply subscribe to the selectionChange event of the MatSelect component.

export class CustomDeliveryDirective implements OnInit, OnDestroy {
  selectionSub: Subscription;

  constructor(
    private host: MatSelect
  ) {
  }

  ngOnInit(): void {
    this.selectionSub = this.host.selectionChange.subscribe(option => {
      console.log(option);
      // Perform desired actions here
    });
  }

  ngOnDestroy(): void {
    this.selectionSub?.unsubscribe();
  }
}

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

The Angular router outlet link is not being recognized

Currently experiencing challenges with router outlets in Angular. I am aiming to create a link structure like "maintopic/subtopicHeadline/subtopic" by defining routes as shown below: export const routes: Routes = [ { path: 'home', component: A ...

Explaining the distinction between include and rootDir in tsconfig.json

According to the information provided, include defines an array of filenames or patterns that are to be included in the program during the compilation process. On the other hand, rootDir specifies the path to the folder containing the source code of the ap ...

Ways to induce scrolling in an overflow-y container

Is there a way to create an offset scroll within a div that contains a list generated by ngFor? I attempted the following on the div with overflow-y: @ViewChild('list') listRef: ElementRef; Then, upon clicking, I tried implementing this with s ...

Unable to load Angular 2 Tour of Heroes application due to Typescript issue

My Angular 2 Tour of Heroes app seems to be stuck on the "Loading..." screen and I can't seem to figure out why. The angular-cli isn't showing any errors either. I'm currently at part five of the tutorial and it's becoming quite frustra ...

The table __EFMigrationsHistory does not exist

Trying to navigate the world of .NET Core and facing some challenges. When I enter the following command in the VS Code terminal dotnet ef database update I encounter the following message: Build started... Build succeeded. info: Microsoft.EntityFramework ...

The error message "Identifier 'title' is not defined. '{}' does not contain such a member angular 8" indicates that the title variable is not recognized or defined in the

Here is the code snippet of my component: import { Router, ActivatedRoute } from '@angular/router'; import { Component, OnInit } from '@angular/core'; import { CategoriesService } from 'src/app/categories.service'; import { P ...

How can a TypeScript object be declared with a single value assignment to itself?

Whenever I try to declare an object and assign a key to itself, I encounter errors. I have attempted different methods, but the error persists. const a = { d:123, a:a//<-TS2448: Block-scoped variable 'a' used before its declaration. } co ...

Angular and Keycloak have conflicting request parameters

I have been using Angular 5 along with Keycloak-Angular version 2.x.x, following the guidelines provided in this documentation: https://www.npmjs.com/package/keycloak-angular Unfortunately, the tutorial does not seem to work for me. When I log in and the ...

Is Angular Module Lazy Loading functioning properly in Chrome?

Is there a way to verify if the JavaScript files are lazy loaded for the currently opened module using Chrome developer tools? ...

Exploring the best way to access ViewContainerRef: ViewChild vs Directive

While researching, I came across a recommendation in the Angular Docs that suggests using a directive to access the ViewContainerRef for creating dynamic components. Here is an example of such a directive: import { Directive, ViewContainerRef } from &apos ...

Error encountered while exporting TypeScript module

While I am working with Angular, TypeScript, and Gulp, my module system is CommonJS. However, I encountered an error when trying to import a module into my main.ts file: Error: Cannot find external module 'modules.ts'. Here is the snippet from ...

After transitioning from deprecated TSlint to ESLint, which style guide is most similar to TSLint in the ESLint ecosystem?

QUERY - Can anyone recommend the closest ESLint style guide to TSLint for an Angular project in VSCode? I'm looking for a out-of-the-box solution that doesn't require me to tweak too many rules in .eslintrc.json file. I initially set up my style ...

Developing Electron applications using Angular-CLI

I am currently developing a desktop application using Electron paired with Angular2 (incorporating Angular-CLI). To utilize Bootstrap within my project, I made sure to include the necessary script files in angular-cli.json under apps[0].scripts as shown b ...

Error: The authentication state for auth0 is not valid

I'm currently working on integrating auth0 into my angular 5 application by following a tutorial found at: The registration process is functioning correctly, but I encounter an issue when attempting to log in. Upon logging in, the console displays th ...

Is there a way to address the sporadic behavior of rxjs combineLatest when used in conjunction with ReplaySubject

My current struggle lies within this particular example: const r1 = new ReplaySubject(2); const r2 = new ReplaySubject(2); r1.next('r1.1'); r1.next('r1.2'); r2.next('r2.1'); combineLatest([r1, r2]).subscribe(console.log); // ...

Tips on fixing the "TypeError: Cannot read properties of undefined (reading 'lookup')" error message that occurs when running npm install

After successfully running npm install on a freshly cloned Angular project, I encountered an error with the node_modules when trying to launch the application using ng s. Could this issue be related to the version of Node.js being used? \node_modules& ...

Using TypeScript to Extract Keys from an Array

Is it possible to mandate the keys of an interface to come from an array of strings: For instance, consider the following array: const myArray = ['key1', 'key2']; I aim to define a new interface named MyInterface that would require al ...

Navigating JSON Objects in Ionic 2

Example of my JSON array structure [{ label: "Interests", datatype: "check", lookupname: "null", order: "05", options: [ 0:{id: "01", value: "Photography"} 1:{id: "0 ...

What is the process for importing a node module into an Angular web worker?

When attempting to import a node module within an Angular 8 web worker, I encounter a compile error stating 'Cannot find module'. Does anyone have a solution for this issue? I created a new worker within my electron project using ng generate web ...

Ways to resolve the issue of the missing property 'ganttContainer' on the 'Gantt' type

I encountered an issue while trying to utilize the Gantt chart feature from the Dhtmlx library in TypeScript. The problem seems to stem from an error during the initialization of gantt. How can I go about resolving this? Below is the relevant code snippet: ...