Search code examples
angularhtmlhiddenangular-ng-if

How to hide link in Angular5/HTML when a certain condition is fulfilled


I am working in Angular5/html. I am kind of stuck at one point.

I have a page where i can add different accounts. I have a link to remove those accounts. Now i want that link to show only when there is more than 1 account added. For only 1 account added i don`t want my account remove link to be shown.

How will i incorporate this condition in my code below? I mean if i use ngif but what will i do in response to ngif to hide the account removal link?

Also for condition in ngif can i specify it here in html (something like that that count is 1 or i is 0 as count is here to tell the number of account) or do i need to write function for it in my ts file.

<li *ngFor="let ac of Accounts; let i = index;">
  <div class="header">
    <h2>{{'account.title' | translate : { count: i + 1 } }}</h2>
    <a [routerLink]="" (click)="removeAccount(i)">{{'account.remove' | translate}}</a>
  </div>
  <account [data]="ac" [id]="i"><account>
</li>

Solution

  • You can use *ngIf on the anchor tag.

    We can get the number of accounts by using the length property of the array Account.length and then check to see if it is greater than > 1.

    Below the anchor tag is only displayed if there is more than 1 element inside the Accounts array.

    <li *ngFor="let ac of Accounts; let i = index;">
        <div class="header">
          <h2>{{'account.title' | translate : { count: i + 1 } }}</h2>
          <a *ngIf="Accounts.length > 1" [routerLink]="" (click)="removeAccount(i)">{{'account.remove' | translate}}</a>
        </div>
        <account [data]="ac" [id]="i">
          <account>
    </li>