Skip to main content

Lab 05: Custom Form Control

πŸ“– Resources​

πŸš€ Starter Code​

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

In this lab, you'll create a reusable custom form control component by implementing the ControlValueAccessor interface. You'll build a toggle switch component that integrates seamlessly with Angular's reactive forms and can be used with formControlName.

πŸ“ Instructions​

Step 1: Implement ControlValueAccessor​

Create a custom form control component:

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();
}
}

Step 2: Use in Form​

Use custom component with formControlName:

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