使用带有Angular 7 Reactive Forms Not Working的mat-option选择“null”值

问题描述 投票:0回答:2

我试图默认选择一个在mat-select中包含“null”[value]的选项。问题是,当显示html时,它不会选择带有“null”[value]的选项。我正在使用Angular 7 Reactive Forms with 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(NULL);

上面的行假定我已经实例化了我的formGroup,其中一个formControl被称为“userId”,而“this.userId”是我的组件的一个属性,它引用了“this.userForm.get('userId')”。

因此,当我将“userId”的formControl值设置为null时,在html中没有选择任何内容。我的印象是你可以将“null”值作为mat-select的选项之一,我错了吗?如果没有,有什么建议可以让我按照我想要的方式工作。

谢谢!

angular angular-material2
2个回答
0
投票

您可以尝试将默认空值作为'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>

0
投票

你不能设置null,因为你有整数属性(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

© www.soinside.com 2019 - 2024. All rights reserved.