Providing Angular multi-select with chips example
The following code implements a reusable Angular component with ControlValueAccessor that provides a multi-select dropdown showing selected items as chips, properly integrates with Reactive Forms, and supports touched, dirty, and disabled states. It uses Angular Material for UI simplicity and includes all essential parts: module, parent form component, and the custom multi-select component with its template and styles.
Below is a concise example of how you can implement a custom multi-select dropdown with chips in Angular using a ControlValueAccessor. It integrates seamlessly with formControlName and correctly supports touched, dirty, and disabled states. Adjust styling and logic to your needs.
Key points
- The custom component (
ChipsMultiSelectComponent) implements ControlValueAccessor.
- It handles
writeValue, registerOnChange, registerOnTouched, and setDisabledState.
- The parent form uses
ReactiveFormsModule with formControlName for binding.
- The component marks itself as touched on blur and marks the control as dirty when user changes selection.
chips-multi-select.component.ts
import {
Component,
Input,
forwardRef,
HostBinding
} from '@angular/core';
import {
ControlValueAccessor,
NG_VALUE_ACCESSOR
} from '@angular/forms';
@Component({
selector: 'app-chips-multi-select',
templateUrl: './chips-multi-select.component.html',
styleUrls: ['./chips-multi-select.component.css'],
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => ChipsMultiSelectComponent),
multi: true
}
]
})
export class ChipsMultiSelectComponent implements ControlValueAccessor {
@Input() options: Array<{ id: number; label: string }> = [];
// Optional styling for disabled state
@HostBinding('class.disabled') disabled = false;
// Internal value
selectedIds: number[] = [];
// Callbacks
private onChange: (value: number[]) => void = () => {};
private onTouched: () => void = () => {};
dropdownOpen = false;
writeValue(value: number[] | null): void {
this.selectedIds = Array.isArray(value) ? value : [];
}
registerOnChange(fn: (value: number[]) => void): void {
this.onChange = fn;
}
registerOnTouched(fn: () => void): void {
this.onTouched = fn;
}
setDisabledState(isDisabled: boolean): void {
this.disabled = isDisabled;
}
toggleDropdown(): void {
if (this.disabled) return;
this.dropdownOpen = !this.dropdownOpen;
}
isSelected(optId: number): boolean {
return this.selectedIds.includes(optId);
}
selectOption(optId: number): void {
if (this.disabled) return;
const alreadySelected = this.isSelected(optId);
if (alreadySelected) {
this.selectedIds = this.selectedIds.filter(id => id !== optId);
} else {
this.selectedIds = [...this.selectedIds, optId];
}
this.onChange(this.selectedIds);
// Mark the control as touched and dirty on user interaction
this.onTouched();
}
removeChip(optId: number): void {
if (this.disabled) return;
this.selectedIds = this.selectedIds.filter(id => id !== optId);
this.onChange(this.selectedIds);
this.onTouched();
}
// Called when the component loses focus
onBlur(): void {
this.onTouched();
}
}
chips-multi-select.component.html
<div class="multi-select" [class.disabled]="disabled" (blur)="onBlur()" tabindex="0">
<div class="chip-container" (click)="toggleDropdown()">
<ng-container *ngIf="selectedIds.length; else placeholder">
<span class="chip" *ngFor="let selId of selectedIds">
{{ options.find(o => o.id === selId)?.label }}
<button type="button" class="close-btn" (click)="removeChip(selId)">×</button>
</span>
</ng-container>
<ng-template #placeholder>
<span class="placeholder">Select options...</span>
</ng-template>
<span class="arrow">{{ dropdownOpen ? '▲' : '▼' }}</span>
</div>
<div class="dropdown" *ngIf="dropdownOpen">
<div
class="dropdown-item"
*ngFor="let opt of options"
[class.selected]="isSelected(opt.id)"
(click)="selectOption(opt.id)"
>
<input type="checkbox" [checked]="isSelected(opt.id)" />
<span>{{ opt.label }}</span>
</div>
</div>
</div>
chips-multi-select.component.css
.multi-select {
display: inline-block;
position: relative;
min-width: 250px;
font-family: Arial, sans-serif;
outline: none;
}
.multi-select.disabled {
opacity: 0.6;
pointer-events: none;
}
.chip-container {
border: 1px solid #ccc;
padding: 6px;
border-radius: 4px;
display: flex;
flex-wrap: wrap;
gap: 4px;
cursor: pointer;
}
.placeholder {
color: #aaa;
}
.chip {
background: #e0e0e0;
border-radius: 16px;
padding: 4px 8px;
display: inline-flex;
align-items: center;
}
.close-btn {
border: none;
background: transparent;
margin-left: 6px;
cursor: pointer;
font-size: 14px;
}
.arrow {
margin-left: auto;
color: #666;
}
.dropdown {
position: absolute;
top: calc(100% + 2px);
left: 0;
right: 0;
border: 1px solid #ccc;
background: white;
z-index: 1000;
max-height: 200px;
overflow-y: auto;
}
.dropdown-item {
padding: 6px 8px;
display: flex;
align-items: center;
cursor: pointer;
}
.dropdown-item:hover {
background: #f5f5f5;
}
.dropdown-item.selected {
background: #e8f4fd;
}
.dropdown-item input {
margin-right: 8px;
}
app.module.ts
Make sure to import ReactiveFormsModule. If using Angular Material icons, inputs, etc., import corresponding modules as needed. This example does not rely on Angular Material.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { ChipsMultiSelectComponent } from './chips-multi-select.component';
@NgModule({
declarations: [
AppComponent,
ChipsMultiSelectComponent
],
imports: [
BrowserModule,
ReactiveFormsModule
],
bootstrap: [AppComponent]
})
export class AppModule {}
app.component.ts
import { Component } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
interface Option {
id: number;
label: string;
}
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
options: Option[] = [
{ id: 1, label: 'Apples' },
{ id: 2, label: 'Bananas' },
{ id: 3, label: 'Cherries' },
{ id: 4, label: 'Dates' }
];
form = this.fb.group({
fruits: [[1, 3], Validators.required] // default selected Apples and Cherries
});
constructor(private fb: FormBuilder) {}
submit(): void {
if (this.form.valid) {
console.log('Form Value:', this.form.value);
} else {
this.form.markAllAsTouched();
}
}
disableControl(): void {
this.form.get('fruits')?.disable();
}
enableControl(): void {
this.form.get('fruits')?.enable();
}
}
app.component.html
<div style="margin: 20px;">
<form [formGroup]="form" (ngSubmit)="submit()">
<label>Favorite fruits (multi-select with chips)</label>
<br />
<app-chips-multi-select
formControlName="fruits"
[options]="options">
</app-chips-multi-select>
<div *ngIf="form.get('fruits')?.touched && form.get('fruits')?.invalid" style="color:red;">
Please select at least one option.
</div>
<div style="margin-top: 10px;">
<button type="submit">Submit</button>
<button type="button" (click)="disableControl()">Disable</button>
<button type="button" (click)="enableControl()">Enable</button>
</div>
</form>
<h4>Form value:</h4>
<pre>{{ form.value | json }}</pre>
<p>Touched: {{ form.get('fruits')?.touched }}</p>
<p>Dirty: {{ form.get('fruits')?.dirty }}</p>
<p>Disabled: {{ form.get('fruits')?.disabled }}</p>
</div>
Notes/Tips:
- The component uses a basic dropdown built with HTML/CSS. You could integrate Angular Material or other UI libraries if desired.
onTouched() is called when the control loses focus or user interaction occurs. onChange() is called whenever selection changes, updating the form control value and setting dirty state.
- Make sure the parent element is focusable (e.g.,
tabindex="0") so the blur event is fired correctly when clicking away.