Search code examples
angulareventsonchange

onSelectionChange in angular, template side checking


I am trying to use onSelectionChange inside mat-select(on mat-option) and I was wondering if it was possible to use following code without touching TS at all, to check $event on template side.

<mat-select>
 <mat-option (onSelectionChange)="handleMetaSignalChange(metaSignal.name,$event);" *ngFor="let metaSignal of metaSignals" [value]="metaSignal">
  {{ metaSignal.name }}
 </mat-option>
</mat-select>

TS side that I want to avoid using

 handleMetaSignalChange(metaSignal: string, event: any) {
    if (event.isUserInput) {    // ignore on deselection of the previous option
      console.log('Meta Signal Changed to ' + metaSignal + event.isUserInput);
    }
 }

I am trying to do something like this:

<mat-option (onSelectionChange)="$event.isUserInput ? 'do one thing' : 'do another thing'" *ngFor="let metaSignal of metaSignals" [value]="metaSignal">

Is it possible to do something like this? Checking $event on template side?


Solution

  • Yes you can do that. But I recommend it only for one liners, simple things. But take a look at reactive forms. Then you don’t need to use onselectionchange at all. You can listen to form changes directly typescript. Your html will be decoupled from any changes of the form. It will contain mostly content