1

I'm trying to add an object array to an array in TypeScript (for an Angular 2 app). Here's a stripped down and simplified version of my code:

mylist.ts:

export class myList {
    constructor(
        Number1: number,
        String1: string
    ){}
}

mylist.component.ts:

import { myList } from './myList';

export class ProductDetailComponent { 

    myNumber: number;
    myString: string;

    myList: Array<myList>;

    constructor() {
        this.myNumber = 10;
        this.myString = "some text";
    }

    addNavigation() {
        this.myList = [ new myList(this.myNumber, this.myString) ];
        console.log(JSON.stringify(this.myList));
    }

}

Output:

[{}]

What am I doing wrong?

1
  • myList is an object, not an array, this is expected behaviour Commented Jun 2, 2016 at 8:29

2 Answers 2

4

You're not binding to a property of MyList thus your object is empty.

Change your class to the following

export class myList {
    constructor(
        public Number1: number,
        public String1: string
    ){}
}

By adding public or private TypeScript will create properties for you. Now the result will be:

[{Number1: val, String1: val}]
Sign up to request clarification or add additional context in comments.

Comments

1

You never set properties of the myList object in its constructor. Try this:

export class myList {
    constructor(Number1: number, String1: string) {
        this.number = Number1;
        this.string = String1;
    }
}

Comments

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.