I'm struggling getting the default selected option working and changing it based on a button click in my Angular 8 (Material) application.
I have created a stackblitz to demonstrate the same.
https://stackblitz.com/edit/angular-hbocgp
I want the region drop down to have default options selected as "North America" and on click of the button i want it to set it to some other options.
app.component.html
<mat-card>
<mat-form-field>
<mat-label>Region</mat-label>
<mat-select [(ngModel)]="regionSelected">
<mat-option *ngFor="let row of regionSelectionList" [value]="row">
{{row.name}}
</mat-option>
</mat-select>
</mat-form-field>
<button mat-raised-button color="primary" (click)="setRegion()">Set Region</button>
</mat-card>
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
regionSelected = { "itemId": 1, "name": "North America Seed" };
regionSelectionList = [
{"itemId":1, "name":"North America Seed"},
{"itemId":67505, "name":"1B: CU2 (North and Far West)"},
{"itemId":67504, "name":"1C: CU1 (Western Cornbelt)"},
{"itemId":67506, "name":"1K: CU3 (Eastern Cornbelt)"},
{"itemId":67503, "name":"1U: CU4 (Southern)"},
{"itemId":65143, "name":"5A: CU5 (Canada)"}
];
setRegion(){
console.log("Clicked");
this.regionSelected = {"itemId":67505, "name":"1B: CU2 (North and Far West)"};
}
}
Update:
Thanks for all the answers, but i ended up using below:
//default
this.regionSelected = this.regionSelectionList[this.regionSelectionList.findIndex(lst => lst.itemId == 1)];
// On button click
this.regionSelected = this.regionSelectionList[this.regionSelectionList.findIndex(lst => lst.itemId == 67505)];