首页 > 解决方案 > 如何使用 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

标签: angularangular-materialangular-reactive-forms

解决方案


将对象设置为 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: ''
    }
  ];

例子


推荐阅读