0

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?

2 Answers 2

1

You need to make a minor change

addToList() {
  myList.push({[this.name]:this.value});
  this.name = "";
  this.value = "";
}
Sign up to request clarification or add additional context in comments.

Comments

1

Use this:

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

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.