0

I'm new to Angular and I am creating a simple to do list app. I want the description, start time and end time that the user inputs to be added to an array as an object when the user clicks the button.

I am able to get the user input when just saving it to property like this:

Typescript:

export class UsersInputComponent {
  descInput: string;
  startInput: number;
  endInput: number;


getUserInput() {
  console.log(this.descInput);
}; // THIS CORRECTLY LOGS THE VALUE WHICH THE USER INPUTS (SEE HTML CODE BELOW)

But when I try to create an object with the input values as properties and then push this to an array, like this....

Typescript:

export class UsersInputComponent {
  descInput: string;
  startInput: number;
  endInput: number;

  list = [];


  itemDetails = {
    desc: this.descInput,
    start: this.startInput,
    end: this.endInput
};


getUserInput() {
  this.list.push(this.itemDetails)
  console.log(this.list);
}; // THIS LOGS AN ARRAY TO THE CONSOLE WITH 1 OBJECT IN, BUT THE PROPERTIES OF THE OBJECT ALL SHOW AS UNDEFINED

The values are undefined when logging to the console. Does anyone know why this is happening?

Here is the html:

<div class="row">
    <div class="col-xs-12 text-center users-input">
        <input class="desc" placeholder="What do you need to do?" type="text" [(ngModel)]="descInput">
        <input class="start" placeholder="Start" type="number" [(ngModel)]="startInput">
        <input class="end" placeholder="End" type="number" [(ngModel)]="endInput">
        <button class="btn btn-primary" (click)="getUserInput()">Add Item</button>
    </div>
</div>
1
  • Could you please provide a StackBlitz sample for the same? Commented Jan 23, 2020 at 11:33

1 Answer 1

1

It's because your ngModels are binded to other class members, not to itemDetails. You either need to change ngModels to following [(ngModel)]="itemDetails.desc" or you can do following when you push to array


getUserInput() {
  this.list.push({
    desc: this.descInput,
    start: this.startInput,
    end: this.endInput
  });
  console.log(this.list);
};

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you Bunyamin, this resolved my issue! This does confuse me slightly though as I thought I was simply assigning the value of this.descInput (which is value I get from the ngModel binding) to 'desc'. Would you be kind enough to explain in more detail why this doesn't work?
It's because, you assign initial values of your ngModels to itemDetails. After then, you never update it. When user interacts with the inputs, this.descInput, this.startInput and this.endInput are indeed getting updated but not itemDetails.

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.