Search code examples
jqueryangulartypescriptangular2-materialize

Pushing into array not working inside jQuery function


I'm using MaterializeCSS's autocomplete with Angular2-Materialize, and I'm trying to push the selected value into an array. However, I'm getting the following error:

Cannot read property 'push' of undefined

Here's my component:

public items: any[] = [];

addItem() {
  $('.autocomplete-content').on('click', 'li', function () {
    let value = $(this).text().trim();
    this.items.push({ [value]: true });
  });
}

If I try to push some random thing outside the jQuery function, it works.

Here's my HTML:

<input type="text" (change)="addItem()" materialize="autocomplete" [materializeParams]="[{'data': myData | async}]">

Solution

  • this in your function refers to the clicked element, not your class' scope. So either use an arrow function

     $('.autocomplete-content').on('click', 'li', ev => {
        let value = $(ev.target).text().trim();
        this.items.push({ [value]: true });
      });
    

    Or bind(this) to make the class' this available in the click handler

     $('.autocomplete-content').on('click', 'li', function (ev) {
        let value = $(ev.target).text().trim();
        this.items.push({ [value]: true });
      }.bind(this));
    

    Note to change $(this) to the element you can pass to the function.

    You could also define something like that in addItem() and use that instead...

    addItem() {
      var that = this;  
      $('.autocomplete-content').on('click', 'li', function () {
        let value = $(this).text().trim();
        that.items.push({ [value]: true });
      });
    }