我有一个表单,用户可以在其中更新用户信息。我想更改html格式,这样用户就可以从下拉菜单中选择选项,而不是输入字符串。我有这样做的总体想法,但仍停留在数据的绑定上。在原始表单中,用户将输入他们来自的状态,我有以下代码。
<mat-form-field>
<input matInput type="text" id="user_state" name="user_state"
placeholder="SC" [(ngModel)]="user.user_state" required>
</mat-form-field>
我知道我使用的是ngModel指令的数据绑定,我该如何将其转换为select options格式,然后将用户选择的数据发送到后端?
下拉列表的官方Angular文档可以在这里找到。正如我所说,你需要一个数组来显示数据。
例如这样的例子。
export class AppComponent {
constructor() {}
countries: any = [
{
full: "Great Britain",
short: "GB"
},
{
full: "United States",
short: "US"
},
{
full: "Canada",
short: "CA"
}
];
selectedCountry: string = "GB";
selectedCountryControl = new FormControl(this.selectedCountry);
}
这是HTML。角度材料-垫选择示例
<div style="padding: 20px;">
<h1>Model Forms</h1>
<div style="padding: 0 0 20px 20px">
<h3>Value string</h3>
<mat-form-field>
<mat-select
name="countryString"
[(value)]="selectedCountry"
placeholder="Country"
>
<mat-option [value]="'GB'">Great Britain</mat-option>
<mat-option [value]="'US'">United States</mat-option>
<mat-option [value]="'CA'">Canada</mat-option>
</mat-select>
</mat-form-field>
Selected = {{selectedCountry}}
</div>
</div>
欲了解更多信息,请点击此处获取此stackblitz
。https://stackblitz.com/edit/angular-material-select-demo-nhweaq