1

I'm trying to make a custom autocomplete component with ag grid. I can't update the returned value with the selected value from the dropdown

In other words :

I type 'A' => I get a list of items => I choose one => the input is updated with the item value => save => I'm getting 'A'

cellEditorSelector :

    cellEditorSelector: (params) => {
      const values = this.articles.map((item) => {
        return {
          text: item.code,
          value: item.id,
        };
      });
      return {
        component: 'autoComplete',
        params: {
          values,
        },
      };
    },

The custom component :

  selector: 's1-ag-grid-auto-complete',
  template: `<div class="flex flex-col gap-1">
    <div class="relative">
      <input
        #input
        class="w-full text-xs rounded-md border-gray-300 shadow-sm pr-6"
        matInput
        (input)="onInputChange($event)"
        (change)="onChange($event)"
        [matAutocomplete]="auto"
        [value]="value"
        s1AutocompleteForceSelection
        type="text"
      />
    </div>
    <mat-autocomplete autoActiveFirstOption="true" #auto="matAutocomplete">
      <mat-divider></mat-divider>
      <mat-option *ngFor="let option of filteredList" [value]="option.value">
        <ng-container>
          <ng-container></ng-container>
        </ng-container>
        <span [title]="option.text" class="text-xs break-words">{{ option.text }} </span>
      </mat-option>
    </mat-autocomplete>
  </div>`,
})
export class AgGridAutoCompleteComponent implements ICellEditorAngularComp {
  public value: any;
  public filteredList;
  public options;
  private params: any;

  public agInit(params: any): void {
    this.params = params;
    this.value = params.value;
    this.options = params.values;
  }

  public onInputChange(event: Event): void {
    const inputValue = (event.target as HTMLInputElement).value;
    if (inputValue != null && inputValue != '') {
      const inputValueLowerCase = inputValue.toLowerCase();
      this.filteredList = (this.options || []).filter((element) => {
        return element.text.toLowerCase().includes(inputValueLowerCase);
      });
    } else {
      this.filteredList = [];
    }
  }

  public onChange($event) {
    this.value = $event.target.value;
  }

  public getValue(): any {
    return this.value;
  }
}

Any ideas?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Almigra
  • 90
  • 6

1 Answers1

2

you can do it like this:

<mat-autocomplete #auto="matAutocomplete" (optionSelected)="input.value = $event.option.value">

Eli Porush
  • 1,339
  • 1
  • 7
  • 18