0

Hi folks running into an error I think is related to scope that I was hoping I could get some advice on. I have an array that I am looping through that I want to push the results to. When I try and push the results to public myArray:Array from within this.test.forEach I get the following error does not exist on type void. Any advice greatly appreciated.

 export class componentName implements OnInit {
 public myArray:Array<any>;

 ngOnInit() {
  this.test = diff(this.example1, this.example2);

  this.test.forEach(function(part){
    let span = document.createElement('span');
    span.appendChild(document.createTextNode(part.value));

    this.myArray.push(span); // error does not exist on type void
  });
}
Galactic Ranger
  • 851
  • 3
  • 14
  • 30
  • 3
    Possible duplicate of [How to access the correct \`this\` context inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback) – eko May 30 '17 at 08:34

1 Answers1

3

Your first error is that you are using the wrong scope for this.

this.test.forEach(function(part){

Should be

 this.test.forEach((part)=>{

and you need to initialize your array.

public myArray:Array<any> = [];
eko
  • 39,722
  • 10
  • 72
  • 98