Home > other >  I want to display data from API, but I don't want to use multiple *ngIfs? Is there another way?
I want to display data from API, but I don't want to use multiple *ngIfs? Is there another way?

Time:12-30

I am getting the Reason property from API, and it has different values. For each specific value I have to display the corresponding value from the table below. But I don't want to use multiple ngIfs, can I do it with mapping or maybe another way?

TABLE

CodePudding user response:

To display different values based on a specific property value, you can use a mapping object to store the values for each property value. Then, you can use the property value as a key to access the corresponding value from the mapping object.

Here's an example of how you might do this in your Angular template:

<div *ngFor="let result of results">

{{mapping[result.reason]}}

In this example, the mapping object is a dictionary that stores the values for each reason property value. The result.reason expression is used as a key to access the corresponding value from the mapping object.

To define the mapping object in your component, you can use a class property:

   export class MyComponent {
   mapping = {
   'reason1': 'Rx not Eligible',
   'reason2': 'Approved',
   'reason3': 'Pending Rx',
   };

   // Other component code
   }

This will display the corresponding value for each result object based on the reason property value.

CodePudding user response:

You can store data from the TABLE in Map object:

const tableMap = new Map([
  ['NOT_ELIGIBLE', 'RX not Eligible'],
  ['YES_ELIGIBLE', 'Approved']
]);

To display a corresponding value:

tableMap.get('NOT_ELIGIBLE'])
  • Related