2

Im retrieving a list of objects from a service in Angular2.

On click I want to put the object from my ngFor onto a new array (with the same interface).

I'm able to display the list with items just fine. I'm also able to display the item I selected in the console, but I'm not able to push this object into a new array with the same interface.

My interface:

export interface Item {
    id: string,
    name: string,
    icon_url: string,
    exterior: string,
    type: string,
    tag: string,
    addedClass: string,
    selected: boolean
}

My component:

import {Component, OnInit, DoCheck} from 'angular2/core';
import {Item} from './../interfaces/interfaces.ts';
import {ItemService} from './../services/item.service.ts';


@Component({
    template: `
        <h2>Add item</h2>
        <div class="itemlist">
            <ul class="items">
                <li 
                    *ngFor="#item of items"
                    [class.selected]="item === selectedItem"
                    (click)="onSelect(item)"
                >
                    <span class="item">
                        {{item.name}}
                    </span>
                </li>
            </ul>
        </div>
    `
})

export class AddTradeComponent implements OnInit {

    public items: Item[];
    public selectedItems: Item[];


    constructor(private _itemService: ItemService) { }

    getUserItems() {
        this._itemService.getUserItems().then(userItems => this.items = userItems);
    
    }

    ngOnInit() {
        this.getUserItems();
    }

    onSelect(item) {
        console.log('items ', item);
        this.selectedItems.push(item);
    }

}

Errors that I'm getting:

Error during evaluation of "click"

TypeError: Cannot read property 'push' of undefined

Logging the object works fine, I just cannot push it onto this.selectedItems.

1
  • That's because you haven't initialized the property. Just change it to public selectedItems: Item[] = []; Commented Dec 29, 2015 at 15:10

1 Answer 1

11

You didn't initialize your arrays. Either initialize the arrays when you declare your member variables:

public items: Item[] = [];
public selectedItems: Item[] = [];

Or initialize them in your constructor:

constructor() {
    this.items = [];
    this.selectedItems = [];
}
Sign up to request clarification or add additional context in comments.

1 Comment

Wow dude, that simple huh. Thanks a ton! Quick question though. Populating the items array worked though, that wasn't initialized either. How does that work?

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.