Search code examples
angularngforangular-ng-if

if an admin is not logged in Can you filter a ngFor to not show the Admin users.


I pull a list of users from a database and in the list of users are Admin users and non admin users. I want to display the admin users if an admin is logged in and not display the admin users if no admin is logged in. This is my current code:

 <tbody>
              <tr *ngFor="let user of users">
                <td>{{user.Salutation.Description === "None" ? "-" : user.Salutation.Description}}</td>
                <td>{{user.FirstName}}</td>
                <td>{{user.Surname}}</td>
                <td>{{user.Region.Description === "None" ? "-" : user.Region.Description}}</td>
                <td>{{user.Institution === null ? "-" : user.Institution}}</td>
                <td>{{user.PrimaryResearchField.Description === "None" ? "-" : user.PrimaryResearchField.Description}}</td>
                <td>{{user.OrcidID === null ? "-" : user.OrcidID}}</td>
                <td>

                  <button title="View" class="btn btn-primary" (click)="viewUser(user.UserKey)">View</button>
                  <button *ngIf="isAdmin || (isSi && userKey == user.UserKey)" title="Edit" class="btn btn-success" (click)="editUser(user.UserKey)">Edit</button>
                  <button *ngIf="isAdmin" title="Delete" class="btn btn-danger" (click)="deleteUser(user.UserKey)">Delete</button>
                </td>
              </tr>
              </tbody>

Thanks in advance.


Solution

  • Short and Simple :

    <ng-template *ngFor="let user of users">
        <tr *ngIf="isAdmin && user.isAdmin"> // check all your conditions here
        .....
        </tr>
    </ng-template>
    

    Another way is :

    1) Filter users array from component side on ngOnInit as per the logged in user

    2) Use pipe function to filter the array