0

i have been trying to display the name of the array item onclick of the user button but onclick of that i m getting name of the user in console but not in page level

this is the app.component.ts file code

  users = DUMMY_USERS;
  selectedUserId?:string;

  get selectedUser(){
    return this.users.find((user) => user.id === this.selectedUserId)!;
  }
  onSelectUser(id:string){
   this.selectedUserId = id;
  }

this is the app.component.html file code

<app-header />
  <ul id="users">
    @for (user of users; track user.id){
      <li >
        <app-users 
        [user]="user"
         (select)="onSelectUser($event)"
        />
      </li>
     }
  </ul>
  @if(selectedUser){
   <app-tasks [name]="selectedUser.name"></app-tasks>
  }@else{
    <p id="fallback">if user not selected anything then else condition will display by default</p>
  }
    
</main>

i have been trying to display the name of the array item onclick of the user button but onclick of that i m getting name of the user in console but not in page level

users.component.html

<div>
        <button (click)="onSelectedUser()">
            <img [src]= "imagePath"> 
           <span>{{user.name}}</span> 
        </button>
    </div>  

users.component.ts

interface User {
  id:string,
  avatar:string,
  name:string
}

@Input ({required:true}) user!: User

@Output() select =new EventEmitter<string>();

    get imagePath(){
      return '/assets/users/'+this.user.avatar;
    }

    onSelectedUser(){
      this.select.emit(this.user.name);
    }
}

this is the code i m trying it i m newly learning angular can some one please explain what is the issue here

1 Answer 1

1

You have to emit the id, not the name from the child (users.component.ts).

onSelectedUser(){
  this.select.emit(this.user.id); // <- changed here!
}

Because selectedUser is looked up using id, not name. Since in your original code you are emitting name, the find statement always returns false, since we are looking up the user name and comparing it with the user id.

get selectedUser(){
    return this.users.find((user) => user.id === this.selectedUserId)!;
}
Sign up to request clarification or add additional context in comments.

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.