Ruschisb
Ruschisb

Reputation: 55

Clicking on the button selects everything, instead of selecting only one Angular 13

So whenever i click on any 'Follower' button it just selects everything there is available instead of just selecting only one... How can i fix this? Example:

enter image description here

It doesn't matter which button i click, it just selects everything available

Here's the code:

follower service

export class FollowerService {

  constructor(private http: HttpClient) { }

  public url: string = environment.apiBaseUrl;

  followUser(userId: number, follower: Follower){
    return this.http.post<Follower>(`${this.url}/follow/user/${userId}`,follower);
  }
  unfollowUser(userId: number) {
    return this.http.delete<Follower>(`${this.url}/unfollow/user/${userId}`);
  }
  getUserFollowers(userId: number) {
    return this.http.get<FollowerModel[]>(`${this.url}/user/${userId}/followers`);
  }
  getUserFollowee(userId: number) {
    return this.http.get<FolloweeModel[]>(`${this.url}/user/${userId}/followee`);
  }
}

follower component

export class FollowersComponent implements OnInit {

  constructor(private userService: UserService, private followerService: FollowerService) { }

  users: User[];
  follower: Follower;
  isFollowed: boolean;
  ngOnInit(): void {
    this.userService.getUsers().subscribe(response => {
      this.users = response;
    });
  }

  followUser(userId: number){
    this.followerService.followUser(userId, this.follower).subscribe(response => {
      this.follower = response;
      this.isFollowed = true;
    });
  }

  unfollowUser(userId: number){
    this.followerService.unfollowUser(userId).subscribe(response => {
      this.isFollowed = false;
    });
  }
}

follower entity

export class Follower {
    id: number;
    followee: User;
    follower: User;
}

follower template

<app-toolbar></app-toolbar>

<div class="main-div" *ngFor="let user of users">
    <div class="users">
        <img [src]="user.imageUrl" alt="user image" height="50px">
        <span>@{{user.username}}</span>
        <div class="button-div" *ngIf="!isFollowed">
            <button mat-raised-button color="primary" (click)="followUser(user.id)">Follow</button>
        </div>
        <div class="button-div" *ngIf="isFollowed">
            <button mat-flat-button color="warn" (click)="unfollowUser(user.id)">Unfollow</button>
        </div>
    </div>
</div>

Upvotes: 1

Views: 57

Answers (1)

RomainG
RomainG

Reputation: 597

It is due to your conditions *ngIf="!isFollowed" and *ngIf="isFollowed". And you set isFollowed to true in followUser method. So, all the user will be selected.

You have do be more specfic, and make something like *ngIf="!user.isFollowed".

Upvotes: 1

Related Questions