Should we use Pipes instead of ternary condition in the template to render something in Angular?

Asked

Viewed 85 times

0

I’m evaluating the best approach to rendering something in my template from a condition, so it avoids rendering and calling unnecessary functions to improve application performance.

I realized that if I have a function in my template to check and return something, whenever there is some action on the screen, these functions are called again. Example:

<div *ngFor="let usuario of usuarios">
   <h3> {{getUserRole (usuario.id)}} </h3>
</div>

And in my TS:

getUserRole (id: number) {
   if (id === 0) {
      return 'Professor'
   } else if (id === 1) {
      return 'Estudante'
   }
}

Whenever I perform an action on my page, for example, one click on a button, this function will be called, even if unnecessarily. An alternative to avoid this is to use pure pipes.

I’m wondering if, when I use the ternary condition in my template, it also occurs, ie:

<div *ngFor="let usuario of usuarios">
   <h3> {{usuario.id === 0? 'Professor': 'Estudo'}} </h3>
</div>

If this also occurs, when I need to use pipes? In all cases I need to render something on a conditional as in the above examples or only if my condition is too heavy (an array with many objects and properties)?

1 answer

1

Actually I would use Pipes only if I want to filter the list of users that will be displayed.

See, in your case whether the user is a teacher or a student, a line will be created and will be displayed.

Now if you wanted to do that same *ngFor display from the users list only teacher lines you could do this with a pipe.

In HTML

 <div *ngFor="let usuario of usuarios | removerAlunosPipe ">
  ...
 </div>

No Ts

@Pipe({name: 'removerAlunosPipe', pure: true})
export class RemoverAlunosPipe implements PipeTransform {
  transform(usuarios: any[]): string[] {
    return usuarios.filter(usuario => usuario.id === 0))
  }
}

Remember that you need to import Pipe into the app module. Using a true Pure pipe it will run only when the user variable changes.

Browser other questions tagged

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