angularangular-material2

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


I am trying to default select an option which contains a "null" [value] in a mat-select. The problem is, it does not select the option with the "null" [value] when the html is displayed. I am using Angular 7 Reactive Forms with Angular Material 7. Here is what I have -

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);

The line above assumes that I have already instantiated my formGroup with one of the formControls being called "userId" and "this.userId" is a property of my component which references "this.userForm.get('userId')".

So when I set the formControl value of "userId" to null nothing is ever selected in the html. I was under the impression that you can have a "null" value as one of the options of a mat-select, Am I wrong? If not, any suggestions on what I can do to get this to work the way I want.

Thanks!


Solution

  • You can not set the null because you have integer property (user.userId), The sample code should be work.

    Template Code:

    <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>
    

    Componet Code

    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