Astrit Shuli
1 min readJun 19, 2023

--

To resolve this issue, you can modify the directive to include a unique identifier for each instance of the directive. One approach is to use the NG_VALUE_ACCESSOR provider and provide a unique useExisting value for each instance. Here's an updated version of the UppercaseDirective that addresses this problem:

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

let nextId = 0;

@Directive({
selector: '[appUppercase]',
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => UppercaseDirective),
multi: true
}
]
})
export class UppercaseDirective implements ControlValueAccessor {
private onChange: (value: any) => void;
private onTouched: () => void;
private id = `appUppercase_${nextId++}`;

@HostListener('input', ['$event.target.value'])
onInput(value: string) {
const transformedValue = value.toUpperCase();
this.onChange(transformedValue); // Update the FormControl value
this.onTouched();
}

writeValue(value: any): void {}

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

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

get controlId(): string {
return this.id;
}
}

In this updated version, a unique identifier (id) is generated for each instance of the UppercaseDirective using a counter (nextId). This ensures that each instance has a unique identifier. The id is then exposed through the controlId getter.

Now, when you apply the appUppercase directive to multiple inputs, each instance will have a unique identifier, preventing the "More than one custom value accessor" error. You can use this identifier in your template or component if needed.

--

--

Astrit Shuli
Astrit Shuli

Written by Astrit Shuli

Full Stack Developer | Angular Specialist

No responses yet