user1553680
user1553680

Reputation: 349

how to get the selected value <mat-select> from HTML into ts file?

I am trying to get the selected value from HTML into ts file . Below is the HTML code which uses Angular material tags

      <mat-form-field [style.visibility]="visibility" >
              <mat-label>Apps</mat-label>
              <mat-select #selectedApp (change)='fetchTableData($event)'>
                    <mat-option *ngFor="let apps of appsList$" [value]="apps.appName">{{apps.appName}}</mat-option>
                    <mat-option [value]="all">All</mat-option>
              </mat-select>
        </mat-form-field>

.ts code

     @ViewChild('selectedApp') selectedApp;

     ngOnInit() {             
             return this.testcaseService.getAll()
         .subscribe(apps => this.appsList$ = apps);

      }

     fetchTableData(event: any){                  

        console.log("Selected App: "+this.selectedApp.Selected);
      } 

I am not sure what am i doing wrong here . Can anyone help me

Upvotes: 0

Views: 1702

Answers (2)

Hien Nguyen
Hien Nguyen

Reputation: 18975

Change your (change) event to fetchTableData($event.value)

 <mat-form-field [style.visibility]="visibility" >
              <mat-label>Apps</mat-label>
              <mat-select #selectedApp (change)='fetchTableData($event.value)'>
                    <mat-option *ngFor="let apps of appsList$" [value]="apps.appName">{{apps.appName}}</mat-option>
                    <mat-option [value]="all">All</mat-option>
              </mat-select>
 </mat-form-field>

and use event as selected value

fetchTableData(event: any) {

    console.log("Selected App: " + event);
  }

Demo https://stackblitz.com/edit/angular-mat-select-data-2

You should not use this.selectedApp.Selected

Upvotes: 0

Prasanth
Prasanth

Reputation: 537

I think you need to use selectionChange event binding from mat-select.

https://material.angular.io/components/select/api

Upvotes: 0

Related Questions