I am working on a form in Angular.
In form.component.ts I have:
import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { FormService } from '../services/form.service';
@Component({
selector: 'my-app',
templateUrl: './form.component.html',
styleUrls: ['./form.component.css'],
})
export class FormComponent {
public accountTypes!: any;
public selectedAccountType: any;
public form: FormGroup = new FormGroup({
first_name: new FormControl('', Validators.required),
last_name: new FormControl('', Validators.required),
email: new FormControl('', [Validators.required, Validators.email]),
account_type: new FormControl(''),
});
constructor(private formService: FormService) {}
ngOnInit(): void {
this.getAccountTypes();
}
public getAccountTypes() {
this.formService.getAccountTypes().subscribe((response) => {
this.accountTypes = response;
});
}
public sendFormData() {
console.log(this.form);
}
}
The form’s template:
<form [formGroup]="form">
<mat-form-field appearance="outline" floatLabel="never">
<mat-label class="mat-label">Fast name:</mat-label>
<input class="mat-input" matInput formControlName="first_name" />
</mat-form-field>
<mat-form-field appearance="outline" floatLabel="always">
<mat-label class="mat-label">Last name:</mat-label>
<input class="mat-input" matInput formControlName="last_name" />
</mat-form-field>
<mat-radio-group
formControlName="account_type"
[(ngModel)]="this.selectedAccountType"
>
<mat-radio-button
*ngFor="let accountType of accountTypes"
[value]="accountType.value"
>
<span class="top-label">{{ accountType.label }}</span>
</mat-radio-button>
</mat-radio-group>
<mat-form-field appearance="outline" floatLabel="never">
<mat-label class="mat-label">Email:</mat-label>
<input class="mat-input" matInput formControlName="email" />
</mat-form-field>
</div>
<div class="center">
<button
(click)="sendFormData()"
mat-raised-button
color="primary"
[disabled]="!form.valid"
>
Submit
</button>
</form>
See this Stackblitz.
The problem
If the user forgets to select a radio button, there is no viable way, from a visual standpoint, to signal the <mat-radio-group> as invalid. I want the first option to be selected by default, instead.
I have not been able to achieve this goal.
What is the easiest and most reliable way to achieve the desired result?