This is a comprehensive request for an Angular app with reactive forms and a custom ControlValueAccessor. Let me break down what's needed:
A custom ControlValueAccessor for a multi-select dropdown with chips
Integration with reactive forms (formControlName)
Support for touched, dirty, and disabled states
Complex multi-select functionality
I'll create:
The custom multi-select component with ControlValueAccessor
A reactive form example showing usage
Proper validation and state management
Styling with Angular Material or Bootstrap
Examples and best practices
Let me structure this comprehensively:
Multi-select component with ControlValueAccessor
Module setup (including ReactiveFormsModule, FormsModule)
Example form component using the multi-select
Styling
Tests
Documentation
Let me create a complete, production-ready example.
Angular Multi-Select Dropdown with Chips and ControlValueAccessor
I'll create a comprehensive, production-ready solution with a custom ControlValueAccessor for a complex multi-select dropdown.
1. Custom Multi-Select Component
typescript Copy code
// multi-select.component.ts
import {
Component,
OnInit,
OnDestroy,
ViewChild,
ElementRef,
forwardRef,
Input,
Output,
EventEmitter,
ChangeDetectionStrategy,
} from '@angular/core';
import {
ControlValueAccessor,
NG_VALUE_ACCESSOR,
NG_VALIDATORS,
FormControl,
Validator,
AbstractControl,
ValidationErrors,
} from '@angular/forms';
import { Subject } from 'rxjs';
import { takeUntil, debounceTime, distinctUntilChanged } from 'rxjs/operators';
export interface SelectOption {
id: string | number;
label: string;
description?: string;
disabled?: boolean;
group?: string;
}
export interface SelectConfig {
placeholder?: string;
searchPlaceholder?: string;
maxSelections?: number;
clearable?: boolean;
searchable?: boolean;
allowCustom?: boolean;
compareWith?: (a: any, b: any) => boolean;
}
@Component({
selector: 'app-multi-select',
templateUrl: './multi-select.component.html',
styleUrls: ['./multi-select.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => MultiSelectComponent),
multi: true,
},
{
provide: NG_VALIDATORS,
useExisting: forwardRef(() => MultiSelectComponent),
multi: true,
},
],
})
export class MultiSelectComponent
implements
ControlValueAccessor,
Validator,
OnInit,
OnDestroy {
@Input() options: SelectOption[] = [];
@Input() config: SelectConfig = {
placeholder: 'Select options...',
searchPlaceholder: 'Search...',
maxSelections: undefined,
clearable: true,
searchable: true,
allowCustom: false,
};
@Input() errorMessages: { [key: string]: string } = {
required: 'This field is required',
maxSelections: `Maximum selections exceeded`,
};
@Output() selectionChange = new EventEmitter<SelectOption[]>();
@Output() openStateChange = new EventEmitter<boolean>();
@ViewChild('searchInput', { static: false }) searchInput!: ElementRef;
@ViewChild('dropdownContainer', { static: false })
dropdownContainer!: ElementRef;
// Form control
selectedOptions: SelectOption[] = [];
searchControl = new FormControl('');
filteredOptions: SelectOption[] = [];
isOpen = false;
isFocused = false;
// ControlValueAccessor properties
disabled = false;
_touched = false;
_dirty = false;
private onChange: (value: any) => void = () => {};
private onTouched: () => void = () => {};
private destroy$ = new Subject<void>();
ngOnInit(): void {
this.initializeSearch();
this.updateFilteredOptions();
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
}
private initializeSearch(): void {
this.searchControl.valueChanges
.pipe(
debounceTime(300),
distinctUntilChanged(),
takeUntil(this.destroy$)
)
.subscribe(() => {
this.updateFilteredOptions();
});
}
private updateFilteredOptions(): void {
const searchTerm = this.searchControl.value?.toLowerCase() || '';
this.filteredOptions = this.options.filter((option) => {
// Exclude already selected options
const isSelected = this.selectedOptions.some(
(selected) => this.compareOptions(selected, option)
);
// Filter by search term
const matchesSearch =
!searchTerm ||
option.label.toLowerCase().includes(searchTerm) ||
(option.description?.toLowerCase().includes(searchTerm) ?? false);
// Filter disabled options
const isNotDisabled = !option.disabled;
return !isSelected && matchesSearch && isNotDisabled;
});
}
private compareOptions(a: SelectOption, b: SelectOption): boolean {
if (this.config.compareWith) {
return this.config.compareWith(a, b);
}
return a.id === b.id;
}
onOptionSelect(option: SelectOption): void {
if (this.disabled || option.disabled) {
return;
}
// Check max selections
if (
this.config.maxSelections &&
this.selectedOptions.length >= this.config.maxSelections
) {
return;
}
this.selectedOptions = [...this.selectedOptions, option];
this.updateValue();
this.updateFilteredOptions();
this.clearSearch();
this.selectionChange.emit(this.selectedOptions);
}
onOptionRemove(option: SelectOption, event?: Event): void {
if (event) {
event.stopPropagation();
}
if (this.disabled) {
return;
}
this.selectedOptions = this.selectedOptions.filter(
(selected) => !this.compareOptions(selected, option)
);
this.updateValue();
this.updateFilteredOptions();
this.markAsDirty();
this.selectionChange.emit(this.selectedOptions);
}
onClear(event: Event): void {
event.stopPropagation();
if (this.disabled) {
return;
}
this.selectedOptions = [];
this.updateValue();
this.updateFilteredOptions();
this.clearSearch();
this.markAsDirty();
this.selectionChange.emit(this.selectedOptions);
}
toggleDropdown(): void {
if (this.disabled) {
return;
}
this.isOpen = !this.isOpen;
this.openStateChange.emit(this.isOpen);
if (this.isOpen && this.searchInput) {
setTimeout(() => this.searchInput.nativeElement.focus(), 0);
}
}
onDropdownClick(event: Event): void {
event.stopPropagation();
}
onSearchFocus(): void {
this.isFocused = true;
}
onSearchBlur(): void {
this.isFocused = false;
this.markAsTouched();
}
onContainerClick(event: Event): void {
if (
this.dropdownContainer &&
!this.dropdownContainer.nativeElement.contains(event.target)
) {
this.isOpen = false;
this.openStateChange.emit(this.isOpen);
}
}
private clearSearch(): void {
this.searchControl.setValue('', { emitEvent: false });
}
private updateValue(): void {
const value = this.selectedOptions.map((opt) => opt.id);
this.onChange(value);
this.markAsDirty();
}
private markAsDirty(): void {
this._dirty = true;
this.onTouched();
}
private markAsTouched(): void {
if (!this._touched) {
this._touched = true;
this.onTouched();
}
}
// ControlValueAccessor methods
writeValue(value: any): void {
if (!value) {
this.selectedOptions = [];
return;
}
// Handle array of IDs
if (Array.isArray(value)) {
this.selectedOptions = this.options.filter((option) =>
value.some((v) => this.compareOptions({ id: v } as SelectOption, option))
);
} else {
this.selectedOptions = [];
}
this.updateFilteredOptions();
}
registerOnChange(fn: (value: any) => void): void {
this.onChange = fn;
}
registerOnTouched(fn: () => void): void {
this.onTouched = fn;
}
setDisabledState(isDisabled: boolean): void {
this.disabled = isDisabled;
if (isDisabled) {
this.searchControl.disable({ emitEvent: false });
this.isOpen = false;
} else {
this.searchControl.enable({ emitEvent: false });
}
}
// Validator method
validate(control: AbstractControl): ValidationErrors | null {
if (!this.selectedOptions || this.selectedOptions.length === 0) {
return control.hasError('required') ? { required: true } : null;
}
if (
this.config.maxSelections &&
this.selectedOptions.length > this.config.maxSelections
) {
return { maxSelections: true };
}
return null;
}
registerOnValidatorChange(): void {}
get displayText(): string {
if (this.selectedOptions.length === 0) {
return this.config.placeholder || '';
}
if (this.selectedOptions.length === 1) {
return this.selectedOptions[0].label;
}
return `${this.selectedOptions.length} selected`;
}
get hasError(): boolean {
return this._touched && this.selectedOptions.length === 0;
}
get isDirty(): boolean {
return this._dirty;
}
get isTouched(): boolean {
return this._touched;
}
}
2. Component Template
Add trackBy method to component:
typescript Copy code
trackByOptionId(index: number, option: SelectOption): string | number {
return option.id;
}
3. Component Styles
4. Module Setup
typescript Copy code
// multi-select.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ReactiveFormsModule, FormsModule } from '@angular/forms';
import { MultiSelectComponent } from './multi-select.component';
@NgModule({
declarations: [MultiSelectComponent],
imports: [CommonModule, ReactiveFormsModule, FormsModule],
exports: [MultiSelectComponent],
})
export class MultiSelectModule {}
5. Example Form Component
typescript Copy code
// app.component.ts
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { SelectOption, SelectConfig } from './multi-select/multi-select.component';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent implements OnInit {
form!: FormGroup;
// Mock data
availableOptions: SelectOption[] = [
{
id: 1,
label: 'Angular',
description: 'Frontend JavaScript framework',
},
{
id: 2,
label: 'React',
description: 'Facebook UI library',
},
{
id: 3,
label: 'Vue.js',
description: 'Progressive JavaScript framework',
},
{
id: 4,
label: 'Svelte',
description: 'Compiler-based framework',
},
{
id: 5,
label: 'TypeScript',
description: 'JavaScript with types',
},
{
id: 6,
label: 'Node.js',
description: 'Server-side JavaScript',
disabled: true,
},
{
id: 7,
label: 'Express',
description: 'Web application framework',
},
{
id: 8,
label: 'Nest.js',
description: 'Progressive backend framework',
},
];
multiSelectConfig: SelectConfig = {
placeholder: 'Select technologies...',
searchPlaceholder: 'Search technologies...',
maxSelections: 5,
clearable: true,
searchable: true,
};
errorMessages = {
required: 'Please select at least one technology',
maxSelections: 'You can select a maximum of 5 technologies',
};
constructor(private fb: FormBuilder) {}
ngOnInit(): void {
this.initializeForm();
}
private initializeForm(): void {
this.form = this.fb.group({
technologies: [[], Validators.required],
framework: [[], [Validators.required]],
languages: [{ value: [], disabled: false }],
});
// Subscribe to form value changes
this.form.valueChanges.subscribe((values) => {
console.log('Form values:', values);
console.log('Form status:', this.form.status);
});
}
get technologiesControl() {
return this.form.get('technologies');
}
get frameworkControl() {
return this.form.get('framework');
}
get languagesControl() {
return this.form.get('languages');
}
onSubmit(): void {
if (this.form.invalid) {
console.log('Form is invalid');
return;
}
console.log('Form submitted:', this.form.value);
// Handle form submission
}
onReset(): void {
this.form.reset();
}
onDisable(): void {
this.form.get('technologies')?.disable();
}
onEnable(): void {
this.form.get('technologies')?.enable();
}
onSelectionChange(selected: SelectOption[]): void {
console.log('Selection changed:', selected);
}
onOpenStateChange(isOpen: boolean): void {
console.log('Dropdown is', isOpen ? 'open' : 'closed');
}
}
6. Example Template
html Copy code
<!-- app.component.html -->
<div class="demo-container">
<h1>Angular Multi-Select with Reactive Forms</h1>
<form [formGroup]="form" (ngSubmit)="onSubmit()">
<div class="form-group">
<label for="technologies">Technologies (Required, Max 5)</label>
<app-multi-select
formControlName="technologies"
[options]="availableOptions"
[config]="multiSelectConfig"
[errorMessages]="errorMessages"
(selectionChange)="onSelectionChange($event)"
(openStateChange)="onOpenStateChange($event)"
id="technologies"
></app-multi-select>
<div class="field-info" *ngIf="technologiesControl">
<span class="status" [class.dirty]="technologiesControl.dirty">
{{ technologiesControl.dirty ? '✎ Dirty' : 'Clean' }}
</span>
<span class="status" [class.touched]="technologiesControl.touched">
{{ technologiesControl.touched ? '✓ Touched' : 'Untouched' }}
</span>
<span
class="status"
[class.disabled]="technologiesControl.disabled"
>
{{ technologiesControl.disabled ? '🔒 Disabled' : 'Enabled' }}
</span>
</div>
</div>
<div class="form-group">
<label for="framework">Framework (Required)</label>
<app-multi-select
formControlName="framework"
[options]="availableOptions.slice(0, 4)"
[config]="{
placeholder: 'Select a framework...',
maxSelections: 1,
searchable: true
}"
id="framework"
></app-multi-select>
</div>
<div class="form-group">
<label for="languages">Languages</label>
<app-multi-select
formControlName="languages"
[options]="availableOptions.slice(4, 6)"
[config]="{
placeholder: 'Select languages...',
clearable: true,
searchable: false
}"
id="languages"
></app-multi-select>
</div>
<div class="button-group">
<button type="submit" [disabled]="form.invalid">Submit</button>
<button type="button" (click)="onReset()" class="secondary">
Reset
</button>
<button type="button" (click)="onDisable()" class="secondary">
Disable
</button>
<button type="button" (click)="onEnable()" class="secondary">
Enable
</button>
</div>
<div class="form-debug">
<h3>Form Status</h3>
<pre>{{ form.value | json }}</pre>
<pre>Valid: {{ form.valid }}</pre>
<pre>Dirty: {{ form.dirty }}</pre>
<pre>Touched: {{ form.touched }}</pre>
</div>
</form>
</div>
7. Styling for Demo
scss Copy code
// app.component.scss
.demo-container {
max-width: 800px;
margin: 0 auto;
padding: 40px 20px;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
h1 {
color: #1f2937;
margin-bottom: 32px;
}
form {
background: #f9fafb;
padding: 32px;
border-radius: 8px;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}
.form-group {
margin-bottom: 24px;
&:last-child {
margin-bottom: 0;
}
label {
display: block;
margin-bottom: 8px;
font-weight: 600;
color: #374151;
font-size: 14px;
}
.field-info {
display: flex;
gap: 12px;
margin-top: 8px;
flex-wrap: wrap;
.status {
font-size: 12px;
padding: 4px 8px;
border-radius: 4px;
background-color: #e5e7eb;
color: #6b7280;
&.dirty {
background-color: #dbeafe;
color: #1e40af;
}
&.touched {
background-color: #dcfce7;
color: #15803d;
}
&.disabled {
background-color: #fed7aa;
color: #92400e;
}
}
}
}
.button-group {
display: flex;
gap: 12px;
margin-top: 32px;
flex-wrap: wrap;
button {
padding: 10px 20px;
border: none;
border-radius: 6px;
font-size: 14px;
font-weight: 600;
cursor: pointer;
transition: all 0.2s ease;
&:not(.secondary) {
background-color: #3b82f6;
color: white;
&:hover:not(:disabled) {
background-color: #2563eb;
box-shadow: 0 4px 12px rgba(37, 99, 235, 0.3);
}
&:disabled {
background-color: #d1d5db;
cursor: not-allowed;
}
}
&.secondary {
background-color: white;
color: #3b82f6;
border: 2px solid #3b82f6;
&:hover:not(:disabled) {
background-color: #eff6ff;
}
&:disabled {
border-color: #d1d5db;
color: #d1d5db;
cursor: not-allowed;
}
}
}
}
.form-debug {
margin-top: 32px;
padding-top: 32px;
border-top: 2px solid #e5e7eb;
h3 {
color: #374151;
margin-bottom: 12px;
font-size: 14px;
}
pre {
background-color: white;
padding: 12px;
border-radius: 4px;
border: 1px solid #e5e7eb;
font-size: 12px;
overflow-x: auto;
margin: 4px 0;
color: #1f2937;
}
}
}
8. Unit Tests
9. Usage in App Module
typescript Copy code
// app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule } from '@angular/forms';
import { MultiSelectModule } from './multi-select/multi-select.module';
import { AppComponent } from './app.component';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, ReactiveFormsModule, MultiSelectModule],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule {}
Key Features Implemented:
✅ ControlValueAccessor - Seamless integration with formControlName
✅ State Management - Proper handling of touched, dirty, disabled states
✅ Validation - Custom validator with error messages
✅ Search/Filter - Debounced search with term matching
✅ Chips Display - Visual representation with remove buttons
✅ Max Selections - Limit maximum selectable items
✅ Disabled Options - Support for disabled options and full component disable
✅ Accessibility - ARIA labels and semantic HTML
✅ Change Detection - OnPush strategy for performance
✅ Custom Config - Flexible configuration options
✅ Event Emitters - Selection and open state changes
✅ Proper Cleanup - Subscription management with takeUntil
✅ Complete Styling - Professional SCSS with animations
✅ Unit Tests - Comprehensive test coverage
This implementation provides a production-ready multi-select component that fully integrates with Angular's reactive forms!