Sub topic 9
Working with select, radio, and checkbox inputs
This chapter assumes you can already bind a text input with [(ngModel)], that your component imports FormsModule, and that you know why every ngModel control needs a name attribute inside a <form>. Here you will see how ngModel adapts to the three input types whose values are not plain strings.
How ngModel adapts to the element
ngModel does not read the DOM itself. It delegates to a value accessor, a small directive that Angular picks from the element's tag and type. The accessor translates between the control's model value and what the element shows.
| Element | Accessor | Model value |
|---|---|---|
| `<input type="text">` and similar | `DefaultValueAccessor` | string |
| `<select>` | `SelectControlValueAccessor` | the selected option's value |
| `<select multiple>` | `SelectMultipleControlValueAccessor` | array of selected values |
| `<input type="radio">` | `RadioControlValueAccessor` | the value of the chosen radio |
| `<input type="checkbox">` | `CheckboxControlValueAccessor` | boolean |
Each accessor has its own rules about what ends up in the model. Most bugs with these inputs come from assuming the checkbox or select behaves like a text box.
A complete example
The component below uses all three input types. It also shows an object-valued select, a boolean checkbox that must be ticked, and a checkbox list that maps to an array.
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
interface Country {
code: string;
name: string;
}
@Component({
selector: 'app-preferences',
imports: [FormsModule],
template: `
<form #f="ngForm" (ngSubmit)="onSubmit()">
<label for="country">Country</label>
<select
id="country"
name="country"
[(ngModel)]="model.country"
[compareWith]="sameCountry"
required
>
<option [ngValue]="null" disabled>Choose a country</option>
@for (c of countries; track c.code) {
<option [ngValue]="c">{{ c.name }}</option>
}
</select>
<fieldset>
<legend>Plan</legend>
@for (p of plans; track p) {
<label>
<input type="radio" name="plan" [(ngModel)]="model.plan" [value]="p" />
{{ p }}
</label>
}
</fieldset>
<label>
<input type="checkbox" name="newsletter" [(ngModel)]="model.newsletter" />
Send me the newsletter
</label>
<fieldset>
<legend>Topics</legend>
@for (t of topics; track t) {
<label>
<input
type="checkbox"
#box
[checked]="model.topics.includes(t)"
(change)="toggleTopic(t, box.checked)"
/>
{{ t }}
</label>
}
</fieldset>
<label>
<input type="checkbox" name="accepted" [(ngModel)]="model.accepted" required />
I accept the terms
</label>
<button type="submit" [disabled]="f.invalid">Save</button>
</form>
`,
})
export class PreferencesComponent {
countries: Country[] = [
{ code: 'DE', name: 'Germany' },
{ code: 'JP', name: 'Japan' },
{ code: 'BR', name: 'Brazil' },
];
plans = ['free', 'pro', 'team'];
topics = ['news', 'tips', 'events'];
model = {
country: null as Country | null,
plan: 'free',
newsletter: false,
accepted: false,
topics: [] as string[],
};
sameCountry = (a: Country | null, b: Country | null) => a?.code === b?.code;
toggleTopic(topic: string, checked: boolean) {
this.model.topics = checked
? [...this.model.topics, topic]
: this.model.topics.filter((t) => t !== topic);
}
onSubmit() {
console.log('Submitted', this.model);
}
}Select: value versus ngValue
An <option> normally carries a string through its value attribute. That is fine for ids and codes. If you write [value]="c" with an object, the DOM converts it to the string "[object Object]", and the model receives that string.
Use [ngValue] when the option represents a non-string value such as an object, a number, or null. The accessor keeps the real value in an internal map and gives the DOM a generated key. When the user picks an option, ngModel receives the original object.
Three details matter:
- Placeholder option.
<option [ngValue]="null" disabled>is selected when the model isnull. Combined withrequired, the control stays invalid until the user chooses a real option. With a plainvalue=""placeholder, the model would hold the empty string instead. - Object identity. By default, Angular finds the selected option by comparing with
===. If the model holds a copy of a country, for example from a server response, no option matches and the select shows blank. Bind[compareWith]to a function that compares a stable key, assameCountrydoes above. Define it as an arrow function property sothisis not an issue and the reference stays the same across change detection. - Initial value. If the model starts as
undefinedand no option matches, the browser shows an empty box, but the model staysundefined. Initialize it deliberately.
For a multi-select, add the multiple attribute and bind to an array:
<select name="languages" multiple [(ngModel)]="model.languages">
<option value="en">English</option>
<option value="de">German</option>
<option value="ja">Japanese</option>
</select>The model becomes string[]. Replace the array rather than mutating it if you want predictable change detection in OnPush components.
Radio buttons: one name, one control
Radios work as a group. RadioControlValueAccessor ties together all radios that share the same name and bind to the same ngModel. In the example, every plan radio uses name="plan" and [(ngModel)]="model.plan", so Angular creates one control whose value is the [value] of the checked radio.
Points to remember:
- Give each radio its own
[value]. Thevalueis what lands in the model, not the label text. - The
nameattribute does two jobs. It registers the control with the parentNgFormand it groups the radios. If you use different names by accident, you get several independent controls and the browser lets the user check more than one. [value]accepts non-string values, such as numbers or objects, on radios.ngModelcompares by identity, so the same object-copy caveat as for select applies.- If the model starts as
nullor holds a value no radio carries, none is checked. That is a valid state, andrequiredon the radios keeps the form invalid until the user chooses one. - Wrap the group in a
<fieldset>with a<legend>. Screen readers announce the legend with each radio, which gives the group an accessible name.
Checkboxes: a boolean, not a list
A single checkbox bound with ngModel gives you true or false. This covers "send me the newsletter" and "I accept the terms."
Adding required to a checkbox does not mean "not empty." Angular's CheckboxRequiredValidator applies to checkboxes with ngModel and treats the control as valid only when the value is true. A false value produces the usual required error, so your normal message code works. This is the standard way to enforce terms acceptance.
If you need the same behavior for dynamic conditions, bind [required]="condition".
Groups of checkboxes
Template-driven forms have no built-in "checkbox list produces an array" feature. Binding every checkbox to ngModel gives you one boolean control each, and each needs its own name. That is often acceptable, and f.value then looks like { news: true, tips: false }.
If you want an array, as in the example, use the plain DOM pattern instead:
- Read the checked state from the element with
[checked]. - Handle
(change)and update the array immutably in the component.
The trade-off is that these checkboxes are not registered as form controls. They do not appear in f.value, do not affect f.dirty, and cannot carry validators. If you need a rule such as "at least one topic," check model.topics.length yourself, for example by disabling the submit button, or move to reactive forms with a FormArray.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Console error "If ngModel is used within a form tag, either the name attribute must be set..." | A control inside `<form>` has no `name` | Add `name`, or `[ngModelOptions]="{standalone: true}"` |
| Select model contains `"[object Object]"` | `[value]` used with an object | Use `[ngValue]` |
| Select is blank although the model has a value | Model holds a different object instance | Add `[compareWith]` |
| Two radios in one group can both be checked | Different `name` values | Use one shared `name` |
| Checkbox model is the string `"on"` or never changes | Bound with `[value]` or `(input)` instead of `ngModel` | Bind `[(ngModel)]` to a boolean |
| Form is valid with the terms box unticked | `required` missing on the checkbox | Add `required` |
Exercise
A select lists products loaded from a server as objects. After a save, the component replaces model.product with a fresh object that has the same id as one in the list, and the select goes blank. What are two ways to fix it, and which is better?
Show answer
Either set model.product to the matching instance from the products array (for example products.find(p => p.id === saved.id)), or bind [compareWith] to a function that compares ids, such as (a, b) => a?.id === b?.id. The compareWith approach is better because it works for any source of the value and does not depend on remembering to look up the original instance.
Exercise
You add a required checkbox for terms acceptance and a user leaves it unticked. What is the control's value, is the control valid, and which error key appears in errors?
Show answer
The value is false, the control is invalid, and errors contains a required key. Angular's checkbox required validator accepts only true.