Search code examples
angularangular-reactive-formsform-controlformgroups

Angular custom component FormControl pass value


I created a custom component for have autocomplete, now I would like to receive the value with FormControl but i can't get the value.

I call the custom component with the selector:

<app-autocomplete-dropdown formControlName="example" [list]="profiloList"></app-autocomplete-dropdown>

But if i try to access to this.form.controls['example'].value I don't get the value.

public inizialize(): void {
        this.form = this.formBuilder.group({
            example: [null]
        });
    }

Custom Component TS File:

export class AutocompleteDropdownComponent implements ControlValueAccessor {

    @Input()
    list: Array<any> = [];

    selectedElement!: Object;

    selectedTitle?: String;

    onChange: any = () => { }
    onTouch: any = () => { }
    touched = false;
    disabled = false;

    constructor() {
    }

    changes(event: Event) {
        if (this.disabled) return
        this.markAsTouched()
        this.selectedElement = event?.target ? (event?.target as HTMLTextAreaElement).value : ''
        this.onChange(this.selectedElement)
    }

    writeValue(obj: any): void {
        this.selectedElement = obj;
    }
    registerOnChange(fn: any): void {
        this.onChange = fn;
    }
    registerOnTouched(fn: any): void {
        this.onTouch = fn;
    }
    setDisabledState?(isDisabled: boolean): void {
        this.disabled = isDisabled;
    }

    markAsTouched() {
        if (!this.touched) {
            this.onTouch();
            this.touched = true;
        }
    }
}

Custom Component HTML File:

<input type="text" class="input" list="list" (keyup)="changes($event)">
    <i class="bz-chevron-down icon arrow"></i>

    <datalist id="list">
        <option *ngFor="let element of list" [value]="element.objectTitle">
            {{element.objectTitle}}</option>
    </datalist>

Solution

  • There are no problems in the code in the question, I do not see the metadata for the AutocompleteDropdownComponent, assuming the problem might be in the metadata

    This is how the meta data for the component should look like

    @Component({
      selector: 'app-autocomplete-dropdown',
      templateUrl: './autocomplete-dropdown.component.html',
      styleUrls: ['./autocomplete-dropdown.component.css'],
      providers: [
        {
          provide: NG_VALUE_ACCESSOR,
          useExisting: forwardRef(() => AutocompleteDropdownComponent),
          multi: true,
        },
      ],
    })
    export class AutocompleteDropdownComponent implements ControlValueAccessor {
    ...
    }