What is the efficient way to check if a string is present in a list of strings in the ngIf angular directive

This is what I am doing currently but wanted to know if there is a better way of doing it instead of using multiple || expressions.

 <button
            *ngIf="(element.account.status && (element.account.status === 'DRAFT') || (element.account.status === 'PENDING') || (element.account.status === 'REVERT') || (element.account.status === 'REVIEW')); else addDisabled"
            id="add-account" mat-icon-button (click)="openDialog(element.accountType)">
            <img src="../../../../assets/add.svg" />
 </button>
 <ng-template #addDisabled>
            <button id="add-account" mat-icon-button [disabled]="true">
              <img class="intro" src="../../../../svgs/add-disabled.svg" />
            </button>
 </ng-template>

25 thoughts on “What is the efficient way to check if a string is present in a list of strings in the ngIf angular directive”

  1. Use a property like this:

     <button
                *ngIf="allowAdd; else addDisabled"
                id="add-account" mat-icon-button (click)="openDialog(element.accountType)">
                <img src="../../../../assets/add.svg" />
     </button>
    

    then in your javascript (e.g in your controller), set the property like this:

    $scope.allowAdd = ['DRAFT', 'PENDING', 'REVERT', 'REVIEW'].includes(element.account.status);
    

    Just make sure you update the boolean property if your account.status
    changes.


    If it’s too complex to keep track of when account.status changes in your controller so you can update the boolean property, you could also add the includes() call directly in the *ngIf as Chris suggested in a comment, but there are two issues:

    1. As your logic changes again (or your list of status grows), it may become unreadable again in the future
    2. Angular would need to execute the includes() call on every change detection cycle (even if the account status didn’t change), in order to check if the condition changed (it may lead to performance issues).

    The View should not keep complex logic checks, this should be in your controller, the view should rely on a simple property instead, this provides a better separation of concerns, improves code readability/maintainability and avoids performance issues.

    Reply

Leave a Comment