angular what is the clean way to hide components based on condition?

Viewed 118

Good day. I have a scenario where components are being shown depending on the condition, I am looking for a clear way ang optimized way to do this. I have a service below that will check 3 conditions like if user exists in the same account , user exists in other account and user does not exists on any account.

if user exists with other account show div 1 and hide div 2 and div 3. If user does not exists on any account show div 2 and hide div 1 and div 3. If user exists in the same account then hide all div.

The showing and hiding of div show always trigger as long as getStarted function is called. Any idea guys ? Thank you.

#let us say I have 3 divs

<div class="1">
</div>


<div class="2">
</div>

<div class="3">
</div>

 getStarted() {
    if (this.userService) {
      this.userService.checkUserEmail(this.accountId,email).subscribe(
        (res: any) => {
          if (res.isSuccess === false) {
            console.log("user already exists on this account")
          } else if (res.isSuccess === true) {
           console.log("user exists on another account")
          } else {
            console.log("User does not exist on any accounts")
          }
        },
        (err: any) => {
           this.notificationService.showError('Something went wrong, Try again later.');
        }
      );
    } else {
      this.notificationService.showError('Something went wrong, Try again later.');
    }
  }
1 Answers

Just create a property like 'userStatus' in componenet ts file and assign values to it from the API response like below, read those respective values in HTML template and compare them using *ngIf. This is very simple version of the implementation, you can use enums as well for probable values. which userStatus property can hold. However below code will work perfectly for you.

userStatus:string;
getStarted() {
    if (this.userService) {
      this.userService.checkUserEmail(this.accountId,email).subscribe(
        (res: any) => {
          if (res.isSuccess === false) {
            userStatus = 'USER_EXISTS'
            console.log("user already exists on this account")
          } else if (res.isSuccess === true) {
            userStatus = 'USER_ON_OTHER_ACCOUNT'
           console.log("user exists on another account")
          } else {
            userStatus = 'USER_ON_NO_ACCOUNT'
            console.log("User does not exist on any accounts")
          }
        },
        (err: any) => {
           this.notificationService.showError('Something went wrong, Try again later.');
        }
      );
    } else {
      this.notificationService.showError('Something went wrong, Try again later.');
    }
  }

and in html

<div *ngIf="userStatus == 'USER_EXISTS'"></div>
<div *ngIf="userStatus == 'USER_ON_OTHER_ACCOUNT'"></div>
<div *ngIf="userStatus == 'USER_ON_NO_ACCOUNT'"></div>
Related