0 day streak
javascript / intermediate
Snippet

Input Transformations with transform

The 'transform' property in @Input allows you to automatically convert incoming values (like strings from HTML attributes) to specific types like booleans or numbers.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
import { Component, Input, booleanAttribute, numberAttribute } from '@angular/core';
@Component({
selector: 'app-user-profile',
standalone: true,
template: `<p>Admin: {{ isAdmin }} | Score: {{ score }}</p>`
})
export class UserProfileComponent {
@Input({ transform: booleanAttribute }) isAdmin: boolean = false;
@Input({ transform: numberAttribute }) score: number = 0;
}
angular
Breakdown
1
transform: booleanAttribute
Converts string attributes like 'isAdmin' or '' to true, and missing attributes to false.
2
transform: numberAttribute
Safely converts string inputs to JavaScript numbers.