0

I am working on a component where I need to show different icons based on a status:

component.html

<app-form-row label="Status">
    <span>
      <i *ngIf="getStatus === 'READY'" class="check circle outline icon green"></i>
      <i *ngIf="getStatus === 'UPDATING'" class="notched circle loading icon orange"></i>
      <i *ngIf="getStatus === 'FAILED'" class="times circle outline icon red"></i>
    </span>
</app-form-row>

component.ts

get getStatus(): string {
    return this.data.status;
  }

Another approach is to move the condition in TS.

component.html

<app-form-row label="Status">
    <span>
      <i [ngClass]=“classByStatus"></i>
    </span>
</app-form-row>

component.ts

get classByStatus(): string {
    return {
      'READY': 'check circle outline icon green',
      'UPDATING': 'notched circle loading icon orange',
      'FAILED': 'times circle outline icon red'
    }[this.data.status];
  }

What are the pros and cons for each approaches?
Any other way to solve this use case?

1
  • 1
    That should probably be ngSwitch, but use whichever you prefer. Commented Aug 10, 2021 at 12:41

1 Answer 1

4

TBH, both are bad approaches. Binding a function to a directive (and also in template interpolation {{ }}) with default change detection strategy would trigger the function for each change detection cycle. It might not be a huge issue initially, but might lead to performance issues later.

Ideal solution would be to apply the conditions directly in the ngClass

<i
  class="circle icon"
  [ngClass]="{
    'READY': 'check outline green', 
    'UPDATING': 'notched loading orange', 
    'FAILED': 'times outline red'
  }[data.status]"
>
</i>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.