IleNea
IleNea

Reputation: 609

Angular 2 show and hide button component

I am trying to show a button (that opens a dialog component) either the current user is admin or not. The problem is that I cannot figure out how.

This is my html of my component:

<app-list [items]="items"
  [page]="'1'"
  [itemsPerPage]="'40'"
  [hasPager]="false"
  [hasFilters]="false"
  [itemInfo]="itemInfo"
  [loading]="loading"
  (onAdd)="handleOnAdd($event)"  -> this one renders the button
  (onMenuItem)="handleOnMenuItem($event)">
</app-list>

In app-list component:

<app-add-button *ngIf="itemInfo.types"
  [hasPager]="hasPager"
  (onAction)="onAdd.emit($event)">
</app-add-button>

// .ts
  @Output() onAdd = new EventEmitter();

What I wanted is to do something like this:

  [loading]="loading"
  *ngIf="loggedUser.coachAdmin"
  (onAdd)="handleOnAdd($event)"
  (onMenuItem)="handleOnMenuItem($event)">

To display the button(or at least making it functional) only if the user is a admin. There is such a way? Or at least how to solve it?

Upvotes: 0

Views: 1012

Answers (4)

John Montgomery
John Montgomery

Reputation: 7096

If you want to display the button only for admins, just add it as a condition in the *ngIf:

<app-add-button *ngIf="itemInfo.types && loggedUser.coachAdmin"
  [hasPager]="hasPager"
  (onAction)="onAdd.emit($event)">
</app-add-button>

If you want it to be functional only for admins, the shortest way would be to do it with a short-circuit logic check:

<app-add-button *ngIf="itemInfo.types"
  [hasPager]="hasPager"
  (onAction)="loggedUser.coachAdmin && onAdd.emit($event)">
</app-add-button>

Upvotes: 0

Ethan
Ethan

Reputation: 29

You can try another way by using [hidden]

[hidden]="loggedUser.coachAdmin !== 'ADMIN'"

Upvotes: 0

tomiplaz
tomiplaz

Reputation: 486

First, to answer your question in the comments:

I am just curious if I can write the ngIf as to show/hide the (onAdd)="handleOnAdd($event)"

No, you can't use *ngIf to "show/hide" the (onAdd) attribute.

If you want to show/hide the component, then the code you posted (*ngIf="loggedUser.coachAdmin") should work fine.

If, however, you want to conditionally execute some code (depending on if user is admin or not), then you should handle that inside your component class definition.

Upvotes: 1

Praveen Kumar
Praveen Kumar

Reputation: 543

I am not sure if coachAdmin is a boolean variable. If not, you would have to change your ngIf to look something like this:

*ngIf="loggedUser.coachAdmin==='ADMIN'"

Upvotes: 1

Related Questions