Angular Radio Button Groups and Select Lists

I found a little issue when creating a simple-ish form in Angular. If you don't know much about Angular then this will probably be TL;DR for you so please ignore this :)

Actually, there are 2 issues:

  1. using 0 for a radio button value does not set the initial checked item,
  2. the initial value must be a string for radio button groups and select lists.

The value behind my options is defined as an enum, thus:

export enum Measure {
  mm,
  inches,
}

The form elements are:

<mat-form-field>
  <mat-select formControlName="defaultMeasure" placeholder="Units" >
    <mat-option value="0">Millimeters</mat-option>
    <mat-option value="1">Inches</mat-option>
  </mat-select>
</mat-form-field>

Note, the enum values are hard coded here. I'm not sure if I can define these with the enum some how...

I'm using Angular Material for this app but, again, this doesn't make a difference to the issue.

The FormGroup has this:

this.form = this.fb.group({
    ...
    'defaultMeasure': [media.defaultMeasure, Validators.required],
    ...

The fix is simple really.

  1. start your enums from 1
export enum Measure {
  mm = 1,
  inches = 2,
}

and don't forget to match these in the hard coded values in the html if you need to.

<mat-form-field>
  <mat-select formControlName="defaultMeasure" placeholder="Units" >
    <mat-option value="1">Millimeters</mat-option>
    <mat-option value="2">Inches</mat-option>
  </mat-select>
</mat-form-field>
  1. use toString() for the control values.
this.form = this.fb.group({
    ...
    'defaultMeasure': [media.defaultMeasure.toString(), Validators.required],
    ...

That's all for now :)