Typeahead – ngModel vs SelectedItem

Currently, if you have <input [(ngModel)]="model" [ngbTypeahead]="fn">, then the model property is a string while you are typing in the input and an Object once you select a value (depending on the type of objects you return from your typeahead).

I think it would be good if we separate these two somehow. This is only my opinion/proposition, but it seems that ngModel could be bound the selected object from the typeahead whereas we could receive the changes to the input in another event if necessary.

I would be interested to know what others think. Thanks

2 thoughts on “Typeahead – ngModel vs SelectedItem

  1. I think that we are going to leave it as-is due to the following reasons:

    • you can use the [editable]="false" option to skip propagation to the model values entered by the user
    • you can use the selectItem event to have an event fired when users make a selection – in this sense separation already exists.

    I’m going to close this one as I believe that we’ve got all the necessary mechanisms in place. Happy to re-consider if you think that we can do better and:

    • have a concrete use-case
    • have a more detailed proposal
  2. selectItem does not works for me.

    I have as dropdown model {type: "query", value: "some test value"}

       selectItem(event: any) {
        const item = event.item;
        if (item.type === 'query') {
          this.form.query = item.value;
        }
      } 
    

    html

      <input
              class="form-control"
              [ngbTypeahead]="query"
              [resultTemplate]="combinedTpl"
              [inputFormatter]="queryFormatter"
              (selectItem)="selectItem($event)"
              type="text"
              id="query"
              name="query"
              [(ngModel)]="form.query"
              autocomplete="off">
    

    So, when you type, the model will be a string. When you select an item, it will run selectItem function and you expect it should set form.query to the string item.value, but instead of that form.query will be whole object {type: "query", value: "some test value"}. I think it is because of this code:

        if (!defaultPrevented) {
          this.writeValue(result);
          this._onChange(result);
        }
    

    when closing the drowpdown, it will set object as a model.

    But, when you use event.preventDefault();, it will set correctly this.form.query, but input value will be cleared/empty, so next time you focus on input, also the model will be cleared.