Amateur coder
Amateur coder

Reputation: 1

How to call function on change event in Angular

I want to call a function, once the value of dropdown is changed.

I have done this without Angular Material. Here's my ts and html files.

  selected="pending";
  
  getRequests(event: any) {
    this.selected = event.target.value;
    if(this.selected=="pending")
    console.log("Inside Pending Requests")
    else
    console.log("Inside Granted Requests")
  }
<div style="margin-left: 70%;" appearance="fill">
  <select (change)="getRequests($event)">
    <option value="pending">Pending</option>
    <option value="granted">Granted</option>
  </select>
</div>

Now, I want to implement this with the help of Angular Material Select Component. Calling the getRequests() function is not working as expected. Somebody please help me on this one. Thanks in advance.

<mat-form-field style="margin-left: 70%;" appearance="fill">
<mat-label>Status</mat-label>
<mat-select [(value)]="selected" (change)="getRequests($event)" >
  <mat-option value="pending">Pending</mat-option>
  <mat-option value="granted">Granted</mat-option>
</mat-select>

Upvotes: 0

Views: 4121

Answers (4)

Chellappan வ
Chellappan வ

Reputation: 27471

Use selectionChange intead of change

<mat-form-field style="margin-left: 70%;" appearance="fill">
<mat-label>Status</mat-label>
<mat-select [(value)]="selected" (selectionChange)="getRequests($event)" >
  <mat-option value="pending">Pending</mat-option>
  <mat-option value="granted">Granted</mat-option>
</mat-select>

Then you should be able to access value from event object value property

 getRequests(event: MatSelectChange) {
    this.selected = event.value;
    if(this.selected=="pending")
    console.log("Inside Pending Requests")
    else
    console.log("Inside Granted Requests")
  }

Working Example

Upvotes: 3

Stacks Queue
Stacks Queue

Reputation: 1152

In Angular Material Design 6 and above, the (change) method was removed. Instead use selectionChange

<mat-select (selectionChange)="doSomething($event)">

Read more about here: Angular 6 Material mat-select change method removed

Upvotes: 3

LaCodeM
LaCodeM

Reputation: 839

your mat-select has an event that is emitted every time selection is changed. It is called selectionChange as per angular documentation: https://material.angular.io/components/select/api so maybe try to chage your (change) to (selectionChange) like this:

<mat-form-field style="margin-left: 70%;" appearance="fill">
<mat-label>Status</mat-label>
<mat-select [(value)]="selected" (selectionChange)="getRequests($event)" >
  <mat-option value="pending">Pending</mat-option>
  <mat-option value="granted">Granted</mat-option>
</mat-select>

Upvotes: 1

Andrew Allen
Andrew Allen

Reputation: 8052

The api is selectionChange i.e. (selectionChange)="getRequests($event)".

See the docs https://material.angular.io/components/select/api

Upvotes: 3

Related Questions