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
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)!;
}