1

I am Using Angular 8 in my project, for reproducing this error I created a stack blitz project https://stackblitz.com/edit/angular-rgwk5k

My code in app.component.ts is

import { Component } from "@angular/core";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  name = "Angular";
  last_element:any;

  ngOnInit() {
    let array1: any[] = [1, 2, 3];
    array1.forEach(function(item, index) {
      this.last_element = item;  // "ERROR TypeError: Cannot set property 'last_element' of undefined"
    }); 
  }
}

I want to assign the value of 'item' to variable last_element, But i showing error "ERROR TypeError: Cannot set property 'last_element' of undefined" in google chrome console , Can anyone help me ?

  • you should use lambda for it. When you create a function `this` has an other meaning. See https://stackoverflow.com/questions/34274520/whats-the-meaning-of-in-typescript-fat-arrow – pL4Gu33 Nov 20 '19 at 15:28

0 Answers0