html - 允许“未定义”作为有效的选择菜单选项(在 Angular 中)?
问题描述
我不确定这是 Angular 问题,还是 HTML 表单的一般限制。
我想要一个具有三个值的选择表单true
: ,false
和, undefined
。请参阅下面的Stackblitz或代码。
<mat-form-field [formGroup]="form">
<mat-select formControlName="test" value="undefined">
<mat-option *ngFor="let v of values"
[value]="v.value">{{ v.display }}</mat-option>
</mat-select>
</mat-form-field>
...以及相应的.ts
文件:
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
public form: FormGroup;
public readonly values: any[] = [
{
display: 'true',
value: true
},
{
display: 'false',
value: false
},
{
display: '--',
value: undefined
}
];
constructor(private readonly fb: FormBuilder) {
this.form = this.fb.group({
test: undefined
});
}
}
但是,在硬编码或工作test
时:true
false
this.form = this.fb.group({
test: true // 'true' or 'false' selected in form.
});
...undefined
不:
this.form = this.fb.group({
test: undefined // '--' option is *not* selected.
});
解决方案
将任何内容设置为都undefined
被认为是一种不好的做法。
在这种特殊情况下,最好的解决方案可能是使用空字符串作为默认值。
如果您查看材料的代码,您会看到 null/undefined 被视为特殊重置值:材料源
推荐阅读
- python - 可以这样使用 return 语句而不返回任何值吗?
- python-3.x - 在seaborn的分组箱线图中突出显示一个点
- java - Android Activity 可重用性
- javascript - 使用 Google Chart API 为堆积条形图着色
- mysql - Laravel groupby 并计算不同的值(多态)
- loops - 如何在迭代 with_item 调试列表时基于传递 when 条件执行 Ansible 任务?
- android - Firebase 数据未显示并出现错误
- postgresql - TOAST 对性能有什么影响?(添加一百个 varchar 列)
- javascript - 用Javascript在桌子周围传递卡片
- matlab - matlab 代码中关于函数的可能错误