2

In my project it's nessesary to use ElementRef's nativeelement.value because of some readonly errors. only my 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
      })
  }

}

doesn't capture the change event from my 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>

while classic inputs do

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

does anyone know a way how to capture the change event from a mat select with a directive?

Noah Bergh
  • 493
  • 4
  • 14

3 Answers3

0

I am not sure which version of Angular Material you are using, but probably change event simple doesn't exist for the mat-select https://stackoverflow.com/a/50223943/9602452

Seems like you have modify your directive for mat-selects

D Pro
  • 1,756
  • 1
  • 8
  • 15
0

To detect changes of mat-select you don't need to HostListener, just subscribe selectionChange of MatSelect

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

  constructor(
    private host: MatSelect
  ) {
  }

  ngOnInit(): void {
    this.selectionSub = this.host.selectionChange.subscribe(option => {
      console.log(option);
      // Do something
    });
  }

  ngOnDestroy(): void {
    this.selectionSub?.unsubscribe();
  }
}
Sadegh
  • 107
  • 1
  • 4
0

You should be listening to the selectionChange event

@Directive({
    selector: '[appMyDirective]',
})
export class MyDirective {
    constructor() {}

    @HostListener('selectionChange', ['$event'])
    onSelectionChange(event: MatSelectChange): void {
        console.log(event);
    }
}
Ben White
  • 263
  • 3
  • 6