首页 > 解决方案 > 允许“未定义”作为有效的选择菜单选项(在 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时:truefalse

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.
});

标签: htmlangular

解决方案


将任何内容设置为都undefined被认为是一种不好的做法。

在这种特殊情况下,最好的解决方案可能是使用空字符串作为默认值。

如果您查看材料的代码,您会看到 null/undefined 被视为特殊重置值:材料源


推荐阅读