Angular 6 - Comparison of values

Asked

Viewed 535 times

0

In the database I save an integer number to represent the user type. The integer number can receive 1, 2, 3, 4, 5, 6 or 7.

When I show the type of user on the screen, I would have to do several *ngIf to show the value in the html component.

<td *ngIf="user.profile == 1"> Administrador </td>
<td *ngIf="user.profile == 2"> Avaliador </td>
<td *ngIf="user.profile == 3"> Responsável </td>

E outros 4 *ngIf para validar o restante...

To not have to do these *ngIf, would you have a better way? I didn’t want to put 7 validations just to show a result in the html component.

  • What was certain was its api to return a field containing this number and a field with the name of the field. Ai Voce would only use thus: {user.}}

  • Vc tbm can use enums in your typescript but it would be a hard-coded solution that if something changes in the backend you have to change in the front tbm.

  • @Eduardovargas as would be the validation to compare with Enum?

1 answer

0


If you will display only one at a time, it may make more sense to "calculate" what will be displayed in the code and show with a function:

TS:

function nomePerfil(perfil: number) : string {
  switch (perfil) {
    case 1: return "Administrador ";        
    case 2: return "Avaliador";    
    ...     
    default: return "";
  }
}

HTML:

<td>{{nomePerfil(user.profile)}}</td>

EDITED

Using the Enum , suggested by @Eduardovargas, the function is much simpler, you just have to declare the Enum:

TS

export enum Perfil {
  Administrador,
  Avaliador,
  Responsável,
}

HTML

<td>{{Perfil[user.profile]}}</td>

I believe calling the Enum how above works, if it doesn’t work you can put this code inside the function nomePerfil previously suggested.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.