InfomediaLtd / angular2-materialize

Angular 2 support for Materialize CSS framework.
https://infomedialtd.github.io/angular2-materialize/
MIT License
407 stars 140 forks source link

Using autocomplete with array of objects #364

Closed renanmoraes closed 7 years ago

renanmoraes commented 7 years ago

I have the following array objects:

captura de tela de 2017-09-01 08-31-39

I need when typing the name of the city it will offer me the ones that correspond with the typed one. With standard array {"Mines": null, "River": null} works perfectly.

I try to do it that way but it really does not work.

  private FindaAllCities() {
    this._user
      .getToken()
      .subscribe(res => {
        this._cities
          .findAll(res.data.token)
          .subscribe(response => {
            this.autocompleteInit = {
              'data': response.data,
              onAutocomplete: (val) => {
                console.log(val);
              },
            };
            console.log(this.autocompleteInit);
            this.cities = response.data;
          });
      });
  }

In reality, if I can get the id informed when it passes data {"Mines": "123456"} would serve me. When I do this, it returns me an error because I think I'm sending an image. I need to know when I clicked the _id of the clicked face.

rubyboy commented 7 years ago

@renanmoraes , unfortunately the MaterializeCSS framework only supports passing the text and getting it back in the onAutocomplete callback: http://materializecss.com/forms.html#autocomplete.

What I suggest you do is map your id (or original object) to the name, and get it using the value. Something like this:

const nameToObject = {};
this.autocompleteInit = {
  'data': {},
  onAutocomplete: (val) => {
    console.log(nameToObject[val]);
  },
};
data.forEach(o => this.autocompleteInit.data[o.name]=null);
data.forEach(o => nameToObject[o.name]=o);