Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Use Null as a value Angular Material Select

I'd like to have a list, where one of the list items is "N/A" and if it is selected, i'd like the formcontrol to have the value null.

In my attempts, I am able to get the formcontrol value to have the value=null but the UI doesnt seem to keep the selected option.

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>

Behavior:

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

like image 520
Sajjan Sarkar Avatar asked Mar 18 '26 06:03

Sajjan Sarkar


1 Answers

Set object to value input of mat-select something like this:

Try this:

<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

As mentioned by @yurzui you can use set empty string '' or -1 to value of short.

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

Example

like image 182
Chellappan வ Avatar answered Mar 19 '26 20:03

Chellappan வ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!