Home > database >  Display selected value on the mat select when return to the page in table
Display selected value on the mat select when return to the page in table

Time:03-25

In my component.html file, I have a table and inside the table body, each row has options which when selected are calling save event, where I am saving the values to database. First time when user visits the page and select the values from dropdown, the selected values are stored in the database and second time when the user visits the page, the selected option value for each row should be displayed. I am not able to figure out how to do this. The options selected for each row can be different Below is my code

component.html

<tbody>
   <tr *ngfor="let row of rows; let i = index">
      <td><span>{{row.name}}</span></td>
      <td>
         <mat-select [multiple] = "false" (selectionChange)="save($event, i)" MatInput 
         placeholder="Favourite Cuisine">
         <mat-option  *ngfor="let item of getCuisineList" 
         [value]="item">
         {{item}}
         </mat-option>
         </mat-select>
      </td>
   </tr>
</tbody>  

In component.ts

```
save(e: MatSelectChange, i): void {
this.cuisine[i] = e.value;
this.itemDeatils["cuisine"] = this.cuisine;
}
```

CodePudding user response:

Well you could use ngModel to store the value. Then your save function would just write that value to the database. When visiting the page again, you could pull the value from the database and set the variable and your mat-select would show the selected value. In the code below, every time you pick an item from the mat-select list, the scope variable faveCuisine gets assigned the value.

HTML

<tbody>
   <tr *ngFor="let row of rows; let i = index">
      <td><span>{{row.name}}</span></td>
      <td>
         <mat-select [multiple]="false" (selectionChange)="save()" MatInput [(ngModel)]="faveCuisine" placeholder="Favourite Cuisine">
         <mat-option  *ngFor="let item of getCuisineList" 
         [value]="item">
         {{item}}
         </mat-option>
         </mat-select>
      </td>
   </tr>
</tbody> 

So in component.ts, there's no need to grab the value. It's already assigned to this.faveCuisine. When coming back to that page, you just need to grab the value from the database and this.faveCuisine=VALUE

faveCuisine:any;

save(): void {
  console.log(`The favorite cuisine is ${this.faveCuisine}`);
}
  • Related