Questions on using imported component

I’m new to angular js 2. Have been going through the tutorials and trying things out but stucked on one issue below. Would anyone know on this?

Below is my code

app.component.ts

import {Component} from 'angular2/core';
import {Items} from './test_items';

@Component({
  selector: 'my-app',
  template:`        
        <div class="content-wrapper">
            <div class="content">
                <ul>
                    <li *ngFor="#hero of heroes">
                        <span>{{hero.id}}</span> {{hero.name}}
                    </li>
                </ul>
            </div>
        </div>
    `
})

export class AppComponent {
  public title = 'Test';
}

test_items.ts

export class Hero {
  id: number;
  name: string;
}

var HEROES: Hero[] = [
  { "id": 11, "name": "Mr. Nice" },
  { "id": 12, "name": "Narco" },
  { "id": 13, "name": "Bombasto" },
  { "id": 14, "name": "Celeritas" },
  { "id": 15, "name": "Magneta" },
  { "id": 16, "name": "RubberMan" },
  { "id": 17, "name": "Dynama" },
  { "id": 18, "name": "Dr IQ" },
  { "id": 19, "name": "Magma" },
  { "id": 20, "name": "Tornado" }
];

export class Items {
  public heroes = HEROES;
}

The list of heroes does not get displayed out as expected. Is there a restriction from getting the list from another component?

2
Leave a Reply

avatar
2 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

import {Component} from 'angular2/core'; import {bootstrap} from 'angular2/platform/browser'; import {Items,Hero} from './comp'; @Component({ selector: 'app', template:` <div class="content-wrapper"> <div class="content"> <ul> <li *ngFor="#hero of heroes"> <span>{{hero.id}}</span> {{hero.name}} </li> </ul> </div> </div> ` }) export class AppComponent { public title = 'Test'; heroes:Hero[]; constructor(items:Items) { this.heroes = items.heroes; } } bootstrap(AppComponent, [Items]); This may help you.

Jason
Guest

The view of the component iterates over the arrary heroes of the component. But there is no such array at all. The only thing that the component has is a title. The fact that a completely unrelated class Items happens to have a fields named heroes is irrelevant. So is the fact that you imported Items in the component. Importing doesn’t mean that all the fields of Items become fields of AppComponent. It simply means that the compiler and the runtime know where to look for the Items class when compiling/executing the code. But since AppComponent doesn’t use the class… Read more »