0

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>
1
  • Your User array in the App component and the template you're showing belong to user-list component. Commented Apr 21, 2021 at 11:43

1 Answer 1

1

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)

}

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

1 Comment

the first solution worked actually, but the second didn't. Thank you

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.