AMAN
AMAN

Reputation: 51

How I can use the If coditIon for not showing some buttons to some users In Angular?

I have an array of blocked_users and now I don't want to show some buttons if a user is in Blocked_users.Here is my angualr.component.html

 <div *ngIf="!(userId in event.blocked_users)">
                  <a class="btn btn-primary" (click)="onjoin(event.id)" >JOIN</a><br>
             </div> 

Here the if condition is not working.So can anyone please tell how to use the if condition if we don't want to show a button to some blocked_users.Any suggestions will be appreciated.

Upvotes: 0

Views: 75

Answers (5)

JossFD
JossFD

Reputation: 2216

You want to check if userId is anywhere in blocked_users. You should have a function in your component that check if this is true or not instead of trying to do it in your template. Your template then needs to use the result of that function in the *ngIf:

Component

//Returns true if the user isn't in the blocked list, otherwise false
get isUserAllowed():boolean{
    return !this.event.blocked_users.some(e=>e.id===this.userId);
}

You can also use includes instead of some here, but Stackblitz sometimes complains about includes and I like comparing just the id, so I used some

Template

<div *ngIf="isUserAllowed">
  <a class="btn btn-primary" (click)="onjoin(event.id)" >JOIN</a><br>
</div> 

Here's a Stackblitz to illustrate. Hope it helps :)

Upvotes: 0

Deepak Chauhan
Deepak Chauhan

Reputation: 1

you can create a function in your component which will check if user exists in blocked_users like this

XYZ.component.html

 *<div *ngIf="!isUserExists(userId)">
     <a class="btn btn-primary" (click)="onjoin(event.id)" >JOIN</a><br>
 </div>* 

XYZ.component.ts

isUserExists(userId)() {
     let result = this.blocked_users.filter(user => user.id == usersId);
     if(result.length > 0) {
        return true;
     } else {
       return false
     }
}

Upvotes: 0

Borshin
Borshin

Reputation: 16

It should be like:

<div *ngIf="!isBlockedUser(userId,event.blocked_users)">
    <a class="btn btn-primary" (click)="onjoin(event.id)" >JOIN</a><br>
</div> 

and in ts:

public isBlockedUser(currentUserId, blockedUserIds): boolean {
    return blockedUserIds.find(id => id == currentUserId) != undefined;
}

Upvotes: 0

wickdninja
wickdninja

Reputation: 1039

A computed property in the component class would do the trick I think.

@Component({
  selector: 'my-app',
  template:`
  <button *ngIf="isUserAllowed">My Button</button>
`
})
export class AppComponent  {
  blockedUsers = [];
  userId = 'someId';

  get isUserAllowed():boolean{
     return !this.blockedUsers.includes(this.userId);
   }
}

Upvotes: 1

Sajeetharan
Sajeetharan

Reputation: 222582

You should *ngIf over an object , it should be something like,

<div *ngIf="!event.blocked_users">
    <a class="btn btn-primary" (click)="onjoin(event.id)" >JOIN</a><br>
</div> 

Upvotes: 0

Related Questions