Reputation: 81
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>
Upvotes: 0
Views: 683
Reputation: 8859
It's because your ngModel
s are binded to other class members, not to itemDetails
. You either need to change ngModel
s 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);
};
Upvotes: 1