8

Summary: I have a working as-you-type field dropdown search. When I choose from the dropdown, which happily sets the field to the object I've received in the search, but unhappily registers THAT change and sends the whole object off to be searched.

HTML:

<form [formGroup]="myForm" novalidate>
  <mat-form-field>
    <input matInput 
    placeholder="SKU / Item Number" 
    [matAutocomplete]="auto" 
    formControlName='itemName'>
  </mat-form-field> 
  <mat-autocomplete #auto="matAutocomplete" [displayWith]="parseDropDownSelection">
      <mat-option 
            *ngFor="let row of searchQueryResult" 
            [value]="row" 
            (onSelectionChange)="onItemSelection($event)">
        <span>{{ row.Name }}</span>
      </mat-option>
  </mat-autocomplete>   
</form>

Setup:

import {FieldSearchServiceItem}     from './../services/field-search.service';

constructor(
    private dialog: MatDialog,
    private formBuilder: FormBuilder,
    private http: HttpClient,
    private appServiceItem: FieldSearchServiceItem,    
    )   {}

ngOnInit()

ngOnInit(){
    this.myForm = this.formBuilder.group
        ({
        itemName: '',
        });

this.myForm
  .get('itemName')
  .valueChanges
  .pipe(
    debounceTime(200),
    switchMap(value => this.appServiceItem.search({name: value}, 1))
    )
  .subscribe(serviceResult => this.searchQueryResult = serviceResult.qResult);
}

The service:

@Injectable()
export class FieldSearchServiceItem 
  {
  constructor(private http: HttpClient) {}
  search(filter: {name: string} = {name: ''}, page = 1): Observable<apiQueryResponseForItem> 
    {
    var queryResponse;
    return this.http.get<apiQueryResponseForItem>(`example.com/search/item/${filter.name}`)
    .pipe(
      tap((response: apiQueryResponseForItem) => 
        {
        response.qResult = response.qResult
          .map(unit => new ItemUnit(unit.Id, unit.Name))
        return response;
        })
      );
    }
  }

The class defs:

export class ItemUnit
    {
    constructor
        (
        public Id:number,
        public Name:string,
        )   {}
    }

export interface apiQueryResponseForItem
    {
    qSuccess: boolean;
    qResult: ItemUnit[];        
    }

I've seen other answers where the solution has been to use the emitEvent:false when setting the value, like so:

this.myForm.get('itemName').patchValue('theDataThatCameBackFromSeach', {emitEvent:false})

That makes sense... but I get the feeling that solution doesn't match up with this observable/injectable/Material approach... mainly because I'm not using a call that does a .setValue() or .patchValue(), I'm guessing there's a binding somewhere in the Material stuff that's handling that.

The server ending up seeing calls like this:

http://example.com/search/item/a                   (when the letter a is typed)
http://example.com/search/item/[object%20Object]   (after clicking the dropdown, JS tries to search 'object' after clumsily falling back to string representation )

My onItemSelection() is currently uninvolved, it's working but does nothing other than dump to the console. The .qResult that's coming back from my searchQueryResult service contains {Id:number,Name:string}. How can I have the field-setting action of the autocomplete still do its work of setting the field, but not creating a change event when it does that, while still honoring the onItemSelection() so I can get my other processing done?

3
  • Did you try putting the <mat-autocomplete> inside the <mat-form-field>? There is no need for (onSelectionChange)="onItemSelection($event)"
    – Nikhil
    May 29, 2020 at 5:15
  • why didn't use optionSelected Output from mat-autocomplete? May 29, 2020 at 9:10
  • Nikhil: yep, tried that, no behavior change when it comes to setting the field, the field is still watched by the injectable and called both on my final keystroke and when set by the Material code when I select the dropdown. May 29, 2020 at 12:27

3 Answers 3

14
+50

I've faced the same issue some time ago, and this is the final solution that I've been using for several inputs in my system.

The steps are:

  1. Realize that there are actually two events here. Something Typed and Value Selected.
  2. Create two observables for the the two events and handle them separately.
class Component {
  ngOnInit() {

    /*       SEPARATE THE EVENTS      */

    // If it's an object, it's been selected.
    // I also don't allow selecting `null` but it's up to you.
    const itemSelected$ = this.myForm.get('itemName').valueChanges.pipe(
      filter(val => typeof val === 'object' && val !== null),
    );
    // If it's a string, it's been typed into the input
    const itemTyped$ = this.myForm.get('itemName').valueChanges.pipe(
      filter(val => typeof val === 'string'),
    );

    /*       HANDLE ITEM SELECTED     */

    itemSelected$.subscribe(item => {
      // If you want, you can also handle "fake" items here.
      // I use this trick to show a placeholder like "Create New Item" in the dropdown
      if (item.id === 0 && item.name === 'Create New Item') {
        this.createNewItem().subscribe(
          newItem => this.myForm.get('itemName').setValue(newItem),
        );
        return;
      }
      // I use this in a custom input component (with ControlValueAccessor)
      // So this is where I notify the parent
      this.onChange(item);
    });

    /*       HANDLE ITEM TYPED        */

    const searchQueryResult$ = itemTyped$.pipe(
      debounce(200),
      tap(value => {/* you could handle starting a loading spinner or smth here */}),
      switchMap(name => this.appServiceItem.search({name}, 1)),
    );

    // now you can either use searchQueryResult$ with async pipe:
    // this.filteredResults$ = searchQueryResult$;
    // or subscribe to it and update a field in your component class:
    searchQueryResult$.subscribe(result => this.searchQueryResult = result);
    // If you subscribe, don't forget to clean up subscriptions onDestroy
  }
}

I've taken the liberty to add a few suggestions and tricks, but you get the general idea - create two separate mutually exclusive observables and handle them separately.

3
  • Excellent, thank you. I did need to use debounceTime in place of debounce in my Angular9 project. This seems to be a complete solution, as I certainly do need to take action upon selection for further processing. Thanks for your help man. 👍 Jun 6, 2020 at 2:04
  • 1
    For folks looking at the answer in the future, I wanted to mention also that the (optionSelected)='onItemSelected($event,i)' set in my html is still causing getting called, only upon the final selection. So if one wasn't doing the fancier "create new item" stuff shown, you can use JUST the itemTyped$ subscription and function portion, and leave the itemSelected$ out. Jun 6, 2020 at 3:00
  • This is nice! Thank you for your idea. I used the same event but filtered the object values filter((searchTerm) => !!searchTerm && typeof searchTerm !== 'object')
    – hyena
    Mar 1, 2022 at 13:16
2

Made a simple app in Stackblitz, you can check it out. Hope I understood correctly your issue.

Main idea is - when user fills in form input we get string, when autocomplete fills it we get ItemUnit. This way we can decide whether to make http request or not.

1
  • I feel like this approach has promise. I see it working in the Stackblitz, but the dropdown wasn't activating in my code. A little weird. Jun 6, 2020 at 1:40
-1

Lets say this was your interface

interface MyClass {
  id: number,
  name: string
}

Inside value changes have a check that

if(!(value instanceof MyClass)) { //callApi }
1
  • The class definition doesn't currently call the api, it has only {}, so I don't see how I could test the input/type within the class to filter the calls. The class is merely a data structure that's sent out to define the @Injectable. Are you saying that you've done this with Material autocomplete? May 26, 2020 at 13:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.