Как использовать Null в качестве значения Angular Выбор материала - PullRequest
2 голосов
/ 06 августа 2020

Я хотел бы иметь список, в котором одним из элементов списка является «N / A», и если он выбран, я бы хотел, чтобы элемент управления формой имел значение null.

В моем попыток, я могу получить значение formcontrol для value = null, но пользовательский интерфейс, похоже, не сохраняет выбранный параметр.

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>

Поведение:

enter image description here

As you can see, I cant seem to make the N/A "stick".

Stackblitz Link:

https://stackblitz.com/edit/angular-material-select-demo-b9fzht?file=src%2Fapp%2Fapp.component.html

Ответы [ 2 ]

1 голос
/ 06 августа 2020

Установите объект для ввода значения 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>

OR

Как упоминалось @yurzui вы можете использовать пустую строку '' или -1 для значения short.

countries: any = [
    {
      full: "Great Britain",
      short: "GB"
    },
    {
      full: "United States",
      short: "US"
    },
    {
      full: "Canada",
      short: "CA"
    },
    {
      full: "N/A",
      short: ''
    }
  ];

Пример

0 голосов
/ 06 августа 2020

Вы можете сделать вот так ..

Задайте value из short в строке, например: short: "null", а затем попробуйте.

См. Изображение

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...