Aller au contenu principal

Lab 05 : Contrôle de Formulaire Personnalisé

📖 Ressources

🚀 Code de Départ

step-5-album-wholesale-v16-post-add-custom-async-validator

Dans ce lab, vous allez créer un composant de contrôle de formulaire personnalisé réutilisable en implémentant l'interface ControlValueAccessor. Vous allez construire un composant toggle switch qui s'intègre parfaitement avec les formulaires réactifs d'Angular et peut être utilisé avec formControlName.

📝 Instructions

Étape 1 : Implémenter ControlValueAccessor

Créez un composant de contrôle de formulaire personnalisé :

import { Component, forwardRef } from '@angular/core';
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';

@Component({
selector: 'app-toggle-switch',
providers: [{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => ToggleSwitchComponent),
multi: true
}]
})
export class ToggleSwitchComponent implements ControlValueAccessor {
value: boolean = false;
onChange = (value: boolean) => {};
onTouched = () => {};

writeValue(value: boolean): void {
this.value = value;
}

registerOnChange(fn: any): void {
this.onChange = fn;
}

registerOnTouched(fn: any): void {
this.onTouched = fn;
}

toggle(): void {
this.value = !this.value;
this.onChange(this.value);
this.onTouched();
}
}

Étape 2 : Utiliser dans le Formulaire

Utilisez le composant personnalisé avec formControlName :

<app-toggle-switch formControlName="highlighted"></app-toggle-switch>
albumForm = this.fb.group({
highlighted: [false]
});