Drobesz
Drobesz

Reputation: 384

Why is my variable undefined in the constructor?

In Angular, I needed to make another variable to control the collapsible rows via ng-bootstrap, but I've made an error and I really don't know what's the problem. Probably the context of this is the key to the answer. I don't know.

So, here's the relevant part of my code (the this.rowsControls array is undefined):

export class TasksComponent implements OnInit {
  tasks: Task[];
  title: string;
  rowsControls: boolean[];

  constructor(private tasksService: TasksService) {
    this.tasksService.getTasks().subscribe(x => { 
      this.tasks = x;
      x.forEach(this.rowsControls.push(true)); 
    });
  }
}

Upvotes: 0

Views: 617

Answers (1)

P.S.
P.S.

Reputation: 16384

You're trying to push inside undefined, just declare an empty array (or not empty, depends on your needs, but rowsControls should be an array):

rowsControls: boolean[] = [];

Upvotes: 3

Related Questions