Issue
I have 2 input fields for name and age, I need to display every user I add in a list. However, instead of the name and age, the following is displayed:
[object Object]’s age is [object Object].
My app.Component.ts file is:
export class AppComponent {
users = []
addUser(name: string , age : number): void {
const uniqueId = Math.random().toString(16)
const newUser = {
id: uniqueId,
name,
age
}
this.users.push(newUser)
}
}
the userList.component.ts file is:
export class UsersListComponent
{
@Input() users;
@Output() adduserEvent = new EventEmitter<Object>()
newUsername: string = ''
newUserAge: number = 0
setNewUserName (userName : string): void {
this.newUsername = userName
}
setNewUserAge (userAge : string): void {
this.newUserAge = parseInt(userAge)
}
addUser(): void {
console.log(this.newUsername, this.newUserAge)
this.adduserEvent.emit({name: this.newUsername , age: this.newUserAge})
this.newUsername = ''
this.newUserAge = 0
}
}
and the HTML parts are:
In app:
<app-users-list [users] = users (adduserEvent)="addUser($event, $event)"></app-users-list>
In userList:
<input #userName type="text" (change)="setNewUserName(userName.value)" [value] = "newUsername"/>
<input #userAge type="number" (change)="setNewUserAge(userAge.value)" [value] = "newUserAge"/>
<button (click) = "addUser()">Add new User</button>
<div *ngFor = "let user of users" class="user-container">
<span>{{user.name}}'s age is {{user.age}}</span>
</div>
Solution
In your case (adduserEvent)="addUser($event, $event)"
value of $event value will be {name: this.newUsername , age: this.newUserAge} and that is an object. When you pass that object, ofc the name and age parameters in addUser function would be objects and not strings…
You should change either to: (adduserEvent)="addUser($event. name, $event.age)" or to change addUser function to accept object a a parameter:
(adduserEvent)="addUser($event)"
addUser(user: {name: string, age: number}): void {
const uniqueId = Math.random().toString(16)
const newUser = {
id: uniqueId,
user.name,
user.age
}
this.users.push(newUser)
}