angular - 如何使用 Null 作为值 Angular Material Select
问题描述
我想要一个列表,其中一个列表项是“N/A”,如果它被选中,我希望表单控件的值为 null。
在我的尝试中,我能够让 formcontrol 值具有 value=null 但 UI 似乎没有保留所选选项。
TS:
import { Component, SimpleChanges, OnChanges } from "@angular/core";
import { FormControl, FormGroup, FormBuilder } from "@angular/forms";
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.scss"]
})
export class AppComponent implements OnChanges {
mainForm: FormGroup;
constructor(private fb: FormBuilder) {
this.mainForm = this.fb.group({
selectedCountryControl: new FormControl("")
});
}
countries: any = [
{
full: "Great Britain",
short: "GB"
},
{
full: "United States",
short: "US"
},
{
full: "Canada",
short: "CA"
},
{
full: "N/A",
short: null
}
];
submit() {
console.log(this.mainForm.value);
}
}
HTML:
<form [formGroup]="mainForm" style="margin-top: 30px;">
<mat-form-field>
<mat-select name="countryReactiveVaraible" formControlName="selectedCountryControl" placeholder="Country">
<mat-option *ngFor="let country of countries" [value]="country.short">
{{country.full}}
</mat-option>
</mat-select>
</mat-form-field>
<button class="btn btn-primary" mat-button (click)="submit()">
Save
</button>
</form>
行为:
如您所见,我似乎无法让 N/A “坚持”。
Stackblitz 链接:
https://stackblitz.com/edit/angular-material-select-demo-b9fzht?file=src%2Fapp%2Fapp.component.html
解决方案
将对象设置为 mat-select 的值输入,如下所示:
尝试这个:
<mat-form-field>
<mat-select #select="matSelect" name="countryReactiveVaraible" formControlName="selectedCountryControl"
placeholder="Country" [compareWith]="compareFn">
<mat-option *ngFor="let country of countries" [value]="country">
{{country.full}}
</mat-option>
</mat-select>
</mat-form-field>
或者
正如@yurzui 所提到的,您可以使用设置空字符串 ''或-1来设置短值。
countries: any = [
{
full: "Great Britain",
short: "GB"
},
{
full: "United States",
short: "US"
},
{
full: "Canada",
short: "CA"
},
{
full: "N/A",
short: ''
}
];
推荐阅读
- mqtt - Wemos 上的 umqtt.robust
- php - 如何在php中删除菜单标题?
- java - 不知道 cookie Idea-f5324dcc=41f745e2-43a5-4a7f-8e31-1b35896e1ac6 代表什么
- php - PHP工匠使用没有端口号的域
- php - 强制在 WooCommerce 结账时仅购买预定义数量
- mysql - 在 mysql 上使用多个 goroutine 进行不同的操作
- c++ - 我应该向 git 添加除 .cpp 之外的其他文件吗?
- centos8 - 添加库用于静态编译 CentOS 8
- javascript - 如何将非匿名“拥有的方法”传递给 addEventListener?
- android - 为用户反馈设置 Android Studio 布局