Kleav James
Kleav James

Reputation: 160

Angular material mat-select: values are function with submit button

In mat-select the values are functions report(),edit(),delete(), then when I click the submit button, the selected value (function) should run. How would I do it?

I am working for the delete() function for now, once I understand the flow, the rest will be easy for me.

component.html file

<ng-container matColumnDef="instrumentName">
   <mat-header-cell *matHeaderCellDef class="header-cell">Instrument Name</mat-header-cell>
   <mat-cell *matCellDef="let element" class="cell">{{ element.instrumentName }}</mat-cell>
</ng-container>

<ng-container matColumnDef="manufacturer">
   <mat-header-cell *matHeaderCellDef class="header-cell">Manufacturer/Model</mat-header-cell>
   <mat-cell *matCellDef="let element" class="cell">{{ element.manufacturer }}</mat-cell>
</ng-container>

<ng-container matColumnDef="_id">
   <mat-header-cell *matHeaderCellDef class="header-cell">Options</mat-header-cell>
      <mat-cell *matCellDef="let element" class="cell">
          <mat-select placeholder="options" [value]>
            <mat-option value="report()">Report</mat-option>
            <mat-option value="edit()">Edit</mat-option>
            <mat-option value="delete()">Delete</mat-option>
          </mat-select>
          <button class="submit-btn" mat-button type="submit">Submit</button>
      </mat-cell>
</ng-container>

component.ts file

delete(instrument: Instruments) {
    this.equipmentService.deleteInstrument(instrument)
      .subscribe(() => console.log('successfully deleted'));
  }

component.service.ts file

deleteInstrument(instrument: Instruments) {
    return this.http.delete<Instruments>(`${this.apiBaseUrl}/equipment/${instrument._id}`);
  }

Upvotes: 1

Views: 3715

Answers (1)

bugs
bugs

Reputation: 15323

You can use two way data binding on your select element and run the selection through a switch case when submit is pressed.

HTML

<mat-select placeholder="options" [(value)]="selection">
    <mat-option value="report">Report</mat-option>
    <mat-option value="edit">Edit</mat-option>
    <mat-option value="delete">Delete</mat-option>
</mat-select>

<button (click)="runSelectedFunction()" class="submit-btn" mat-button type="submit">Submit</button>

TS

export class YourClass{
  selection: string = 'report';

  report() {
    console.log('report');
  }

  edit() {
    console.log('edit');
  }

  delete() {
    console.log('delete');
  }

  runSelectedFunction() {
    switch (this.selection) {
      case 'report':
        this.report();
        break;
      case 'edit':
        this.edit();
        break;
      case 'delete':
        this.delete();
        break;
    }

  }
}

Working demo

Upvotes: 1

Related Questions