【发布时间】:2026-01-06 11:55:01
【问题描述】:
我正在努力让默认选择的选项工作并根据我的 Angular 8(材料)应用程序中的按钮单击来更改它。
我创建了一个 stackblitz 来演示。
https://stackblitz.com/edit/angular-hbocgp
我希望区域下拉菜单将默认选项选为“北美”,并在单击按钮时将其设置为其他选项。
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)"};
}
}
更新:
感谢所有答案,但我最终使用了以下内容:
//默认
this.regionSelected = this.regionSelectionList[this.regionSelectionList.findIndex(lst => lst.itemId == 1)];
// 按钮点击
this.regionSelected = this.regionSelectionList[this.regionSelectionList.findIndex(lst => lst.itemId == 67505)];
【问题讨论】: