Sub topic 3
Working with Select, Radio, and Checkbox Inputs
Assume you know Angular components, template syntax, and basic HTML forms. Template-driven forms use HTML structure and directives to create the form model.
Select, radio, and checkbox controls
Give every ngModel control a name. A select stores one option value. Radio buttons share a name and store one selected value. A checkbox stores a Boolean.
<select name="role" [(ngModel)]="model.role">
<option value="user">User</option>
<option value="admin">Admin</option>
</select>
<label>
<input type="radio" name="contact" value="email"
[(ngModel)]="model.contact">
Email
</label>
<label>
<input type="radio" name="contact" value="phone"
[(ngModel)]="model.contact">
Phone
</label>
<label>
<input type="checkbox" name="terms" [(ngModel)]="model.terms">
Accept terms
</label>Group related controls
ngModelGroup nests controls in the form value and exposes group validity.
<div ngModelGroup="address" #address="ngModelGroup">
<input name="city" [(ngModel)]="model.address.city" required>
<input name="postcode" [(ngModel)]="model.address.postcode" required>
</div>
<p>Address valid: {{ address.valid }}</p>The form value now contains address.city and address.postcode.
Custom and cross-field validation
A custom validator is a directive that implements Validator and returns an error object or null. Register it with NG_VALIDATORS.
@Directive({
selector: '[forbiddenName]',
standalone: true,
providers: [{
provide: NG_VALIDATORS,
useExisting: ForbiddenNameDirective,
multi: true
}]
})
export class ForbiddenNameDirective implements Validator {
@Input() forbiddenName = '';
validate(control: AbstractControl): ValidationErrors | null {
return control.value?.toLowerCase() === this.forbiddenName.toLowerCase()
? { forbiddenName: true }
: null;
}
}Cross-field rules belong on a group validator because the validator needs several control values. For example, compare password and confirmPassword from the group and return { mismatch: true } when they differ.
Tune and defer validation
ngModelOptions controls update timing:
<input name="username" [(ngModel)]="model.username"
[ngModelOptions]="{ updateOn: 'blur' }">For server-backed checks, an asynchronous validator returns an Observable or Promise. Use it for checks such as username availability, not simple local rules.
flowchart TD
Input --> Local["Local validator"]
Local --> Async["Async validator"]
Async --> Status["valid, invalid, or pending"]Test the form
Create a component with TestBed, query the input, set its value, dispatch input, and inspect the form directive or rendered error. Test both invalid and valid paths, including custom and asynchronous validation.
Exercise
What value does a checkbox bound with [(ngModel)] normally produce?
Show answer
A Boolean: true when checked and false when unchecked.