0

I want put 10 numbers in my Array , but I get undefined

public arrayDrag: number[];

ngOnInit() {
    this.arrayDrag = new Array(); //or   this.arrayDrag = new Array(10)
}

  rowDragEnd(event) {
    let max = 0;
    this.arrayDrag = new Array();  //or   this.arrayDrag = new Array(10)

    this.gridApi.forEachNodeAfterFilterAndSort(function(node) {
      if (max < 10) {
        this.arrayDrag.push(node.data.point);
        console.log('add', node.data.point);
        max += 1;
      }
    });
  }

I declared to arrayDrag with (0) or (10) and when my event is calls (rowDragEnd), I get error "undefined" the this.arrayDrag.push(

EduBw
  • 866
  • 5
  • 20
  • 40
  • What's the _full error_? Are you sure that the issue isn't `node.data.point`? – random_user_name May 30 '18 at 14:55
  • Possible duplicate of [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – ConnorsFan May 30 '18 at 15:07

1 Answers1

6

You need to use an arrow function to maintain the scope to your component.

this.gridApi.forEachNodeAfterFilterAndSort((node) => {
  if (max < 10) {
    this.arrayDrag.push(node.data.point);
    console.log('add', node.data.point);
    max += 1;
  }
});

In the code you posted you are using a function so this refers to the function and not your component.

Teddy Sterne
  • 13,774
  • 2
  • 46
  • 51
  • Perfect, thanks, But I don't understand why with function () {} undefined ... can you tell me ? – EduBw May 30 '18 at 15:01
  • When you declare a function as `function () {}` within the function `this` refers to the function and not the component so the function does not have a property of `arrayDrag`. When you declare the function as `() => {}` then within the function `this` refers to the outer scope. – Teddy Sterne May 30 '18 at 15:12