使用 mat-option 和 Angular 选择 "null" 值 7 Reactive Forms Not Working

Selecting a "null" value using mat-option with Angular 7 Reactive Forms Not Working

我正在尝试默认 select 一个选项,该选项在 mat-select 中包含 "null" [值]。问题是,当显示 html 时,它不会 select 带有 "null" [值] 的选项。我正在使用 Angular 7 反应形式和 Angular Material 7。这就是我所拥有的 -

Html:

<mat-select placeholder="User" formControlName="userId">
  <mat-option [value]="null">None</mat-option>
  <mat-option *ngFor="let user of users" [value]="user.userId">
      {{ user.name }}
  </mat-option>
</mat-select>

Component.ts:

this.userId.setValue(空);

上面的行假设我已经实例化了我的 formGroup,其中一个 formControls 被称为 "userId" 并且 "this.userId" 是我的组件的一个 属性,它引用 "this.userForm.get('userId')".

因此,当我将 "userId" 的 formControl 值设置为 null 时,select 不会在 html 中编辑任何内容。我的印象是您可以将 "null" 值作为 mat-select 的选项之一,我错了吗?如果没有,关于我可以做些什么来让它按照我想要的方式工作的任何建议。

谢谢!

您能否尝试将默认空值作为 'users' 数组的第一个选项。

this.users.unshift({
  userId: null,
  name: 'select'
});

模板:

<mat-select placeholder="User" formControlName="userId">
  <mat-option *ngFor="let user of users" [value]="user.userId">
      {{ user.name }}
  </mat-option>
</mat-select>

您不能设置空值,因为您有整数 属性 (user.userId),示例代码应该可以工作。

模板代码:

<form [formGroup]="patientCategory">
    <mat-form-field class="full-width">
        <mat-select placeholder="Category" formControlName="patientCategory">
            <mat-option [value]="0">None</mat-option>
            <mat-option *ngFor="let category of patientCategories" [value]="category.id">
                {{category.name}} - {{category.description}}
            </mat-option>
        </mat-select>
    </mat-form-field>

    <p>{{patientCategory.get('patientCategory').value | json}}</p>
</form>

组件代码

import { Component, ViewChild } from '@angular/core';
import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms';

/**
 * @title Basic table
 */
@Component({
  selector: 'table-basic-example',
  styleUrls: ['table-basic-example.css'],
  templateUrl: 'table-basic-example.html',
})
export class TableBasicExample {
  patientCategory: FormGroup;

  patientCategories = [{
    id: 1,
    name: 'name 1',
    description: 'description 1'
  }, {
    id: 2,
    name: 'name 2',
    description: 'description 2'
  }, {
    id: 3,
    name: 'name 3',
    description: 'description 3'
  }]

  constructor(private fb: FormBuilder) { }

  ngOnInit() {

    this.patientCategory = this.fb.group({
      patientCategory: [null, Validators.required]
    });

    //const toSelect = this.patientCategories.find(c => c.id == 3);
    this.patientCategory.get('patientCategory').setValue(0);
  }
}

Demo