Martijn.Veenstra
Martijn.Veenstra

Reputation: 121

Push object into new array with interfaces in Angular2

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.

Upvotes: 2

Views: 18672

Answers (1)

Michael Kang
Michael Kang

Reputation: 52867

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 = [];
}

Upvotes: 11

Related Questions