user3334871
user3334871

Reputation: 1361

Angular 2 - Object Map with custom key fields?

I have a list in my Angular app that I am trying to POST with. The user is able to enter in their own key-value pair. So I have two inputs like:

<input type="text" id="name" [(ngModel)]="name" />
<input type="text" id="value" [(ngModel)]="value" />
<button class="btn" (click)="addToList()" />

And my TS file would have something like:

myList : any = [];
name = "";
value = "";

addToList() {
  //I wanted to do myList.push({this.name:this.value}), but it didn't work
  myList[this.name]=this.value;
  this.name = "";
  this.value = "";
}

onSubmit() {
    var submitJSON = {
       userList = myList,
       ....
    }
    console.log(submitJSON);
}

However, in my submit flow, it shows the object as empty, and the length as zero. When I use console commands, I can see the list is populated at the time I construct my submit object, but it isn't added to my submit object, and the length is 0. When I inspect in the console, I can see my object, I can see it has a key-value pair in the list, but the length is 0. Am I doing something wrong? Should I not be pushing to my list in the way that I am?

Upvotes: 0

Views: 316

Answers (2)

Shaharyar Kirmani
Shaharyar Kirmani

Reputation: 305

You need to make a minor change

addToList() {
  myList.push({[this.name]:this.value});
  this.name = "";
  this.value = "";
}

Upvotes: 1

Manu Bhardwaj
Manu Bhardwaj

Reputation: 1051

Use this:

myList.push({[this.name] : this.value});

Upvotes: 1

Related Questions