how to call a method when mat-option is selected (angular)?

8.2k Views Asked by At

I am new to Angular and I want to call a specific method, only when option3 is selected. I am struggling to solve this and cannot find much information on this on the internet.

When I call option3, the output is empty.

Here is my code so far:

app.component.html:

<mat-form-field>
  <mat-label>Select an option</mat-label>
  <mat-select [(value)]="selected" >
    <mat-option>None</mat-option>
    <mat-option value="option1">Option 1</mat-option>
    <mat-option value="option2">Option 2</mat-option>
    <mat-option selectionChange="greet($event)">Option 3</mat-option>
  </mat-select>
</mat-form-field>

<p>You selected: {{selected}}</p>

app.component.ts:

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'materialdesign';
  selected = 'option33';


  greet() {
    this.selected = 'it works';
  }
}
4

There are 4 best solutions below

2
On BEST ANSWER

If you want to listen to an event from an Angular component, you need to add parenthesis around the event:

<mat-option (selectionChange)="greet($event)">Option 3</mat-option>

Then your should method should start executing.

5
On

Try like below,

selectionChange event is part of mat-select. So Just call the method when you select an option from the list. And based on the value of the option selected, execute your required code.

.html

<mat-form-field>
  <mat-label>Select an option</mat-label>
  <mat-select [(value)]="selected" (selectionChange)="greet($event)">
    <mat-option>None</mat-option>
    <mat-option value="option1">Option 1</mat-option>
    <mat-option value="option2">Option 2</mat-option>
    <mat-option value="option3">Option 3</mat-option>
  </mat-select>
</mat-form-field>

.ts

selected: string;

greet(event) {
  if(event.value === 'option3') {
    // Execute the required code
  }
}
1
On

try this

<mat-form-field>
  <mat-label>Select an option</mat-label>
  <mat-select [(value)]="selected" (selectionChange)="inputChange()">
    <mat-option>None</mat-option>
    <mat-option value="option1">Option 1</mat-option>
    <mat-option value="option2">Option 2</mat-option>
    <mat-option value="option3">Option 3</mat-option>
  </mat-select>
</mat-form-field>

<p>You selected: {{selected}}</p>

in component.ts

title = 'materialdesign';
  selected = 'option33';
inputChange(){
  if(this.selected == 'option3'){
    this.greet();
  }
}

  greet() {
    this.selected = 'it works';
  }

stackblitz example

4
On

Simply define click event handler on the specific mat-option element.

<mat-option value="option3" (click)="greet()">Option 3</mat-option>