In Angular, radio button elements with the same name attribute are treated as a single control system. This means that multiple radio buttons with the same name act as one input with only one output value (similar to a select element with multiple options). The selected radio button determines the value of the control. Conversely, in Angular, the value of the control can also determine which radio button is selected. For instance, if Radio Button A has a value of "1" and Radio Button B has a value of "2", setting the control's value to "2" during initialization will automatically select Radio Button B.
To bind the ngModel directive to a default value in a radio button element, use the following syntax:
[ngModel]="defaultValue"
Example TypeScript component:
import { Component, VERSION } from '@angular/core';
import { NgForm } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
name = 'Angular ' + VERSION.major;
defaultPromo = 'limitedPromo';
icons: any[] = [
{ id: 1, name: 'icon-1' },
{ id: 2, name: 'icon-2' },
{ id: 3, name: 'icon-3' },
];
onNgSubmit(form: NgForm) {
if (form.valid) {
console.log(form);
} else if (form.invalid) {
form.form.markAllAsTouched();
}
}
}
Template:
<form class="custom-form" (ngSubmit)="onNgSubmit(formInstance)" #formInstance="ngForm">
<label>
<span> Name :</span>
<input
type="text"
name="name"
class="input"
minlength="5"
required
ngModel
#name="ngModel"
/>
<ng-container *ngIf="name.touched && name.invalid">
<div class="error-message" *ngIf="name.errors?.required">
This field is required
</div>
<div *ngIf="name.errors?.minlength">Please enter at least 5 characters.</div>
</ng-container>
</label>
<label>
<span> Icons :</span>
<select
name="icon"
class="input input--select"
required
ngModel
#icon="ngModel"
>
<option *ngFor="let icon of icons" [ngValue]="icon.name">
{{ icon.name }}
</option>
</select>
<ng-container *ngIf="icon.touched && icon.invalid">
<div class="error-message" *ngIf="icon.errors?.required">
Please select an icon
</div>
</ng-container>
</label>
<button type="submit" class="btn btn--green">Submit</button>
<pre>{{ formInstance.form.value | json }}</pre>
</form>