1

I'm trying to dynamically populate an array in Angular2. Below is my

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

@Component({
    selector: 'pm-app',
    templateUrl: 'app/app.component.html'
})
export class AppComponent {        
    ngOnInit(): void {
        let numbers: number[] = [];
        for (var i=1; i <= 9; i++) {
            numbers.push(i);
        }
    }
}

Below is the HTML content:

<div id="numbers-frame">
    <div class="well">
        <div *ngFor="let number of numbers; let i = index">
          {{i}} {{number}}
        </div>
    </div>
</div>

I'm not getting any output at all. Can anyone please tell what am I doing wrong in this? Thanks.

1
  • numbers variable is is local variable move it to the class level . Commented Dec 1, 2016 at 16:26

1 Answer 1

4

Angular2 looks at the component as context. You should declare numbers property within your component:

export class AppComponent {   
  numbers: number[] = [];

  ngOnInit(): void {
    for (var i=1; i <= 9; i++) {
      this.numbers.push(i);
    }
  }
}

Plunker Example

Sign up to request clarification or add additional context in comments.

1 Comment

@Pankaj Parkar Possible you're right. Anyway angular factory contains code self.context.numbers and it's undefined in his case

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.