FREE SNIPPET
Back to SnippetsAngular 21: clean event value helpers (no template casting)
A tiny pattern that avoids `($event.target as HTMLInputElement)` in templates and keeps control-flow pages clean.
Angular 21+SignalsTemplates
Receipt: no template errors. ever again.
What this is
Stop fighting the template parser. Read values safely in TS.
Angular templates are intentionally limited. Casting inside HTML tends to explode on you at the worst time.
This pattern keeps templates readable and pushes the “DOM weirdness” into a couple of tiny helpers.
- Drop helpers into any component (or a tiny util).
- Use `(input)="onSearch($event)"` and keep it boring.
Code
Language: ts
// Helpers (component or util)
export function inputValue(ev: Event): string {
const el = ev.target as HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement | null;
return el?.value ?? '';
}
export function inputChecked(ev: Event): boolean {
const el = ev.target as HTMLInputElement | null;
return !!el?.checked;
}
// Usage in a component
q = signal('');
onSearch(ev: Event) {
this.q.set(inputValue(ev));
}
onActiveToggle(ev: Event) {
this.activeOnly.set(inputChecked(ev));
}