javascript / intermediate
Snippet
Input-Transformationen mit transform
Die 'transform'-Eigenschaft in @Input ermöglicht es, eingehende Werte (wie Strings aus HTML-Attributen) automatisch in bestimmte Typen wie Booleans oder Zahlen umzuwandeln.
snippet.js
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
Erklärung
1
transform: booleanAttribute
Konvertiert String-Attribute wie 'isAdmin' oder '' zu true, und fehlende Attribute zu false.
2
transform: numberAttribute
Konvertiert String-Eingaben sicher in JavaScript-Zahlen.