'how to check if variable exists in angular?

Here is my example:

      <li class="list-group-item" *ngIf="request.answer.user">
         <a href="" class="d-flex flex-column align-items-center">
           <span class="icofont-law-order icofont-2x"></span>
           <p>user</p>
         </a>
      </li>

I want to show the li only if the variables exists. In some cases, there is no answer.



Solution 1:[1]

If you go for *ngIf="true ? something : somethingElse" it is pretty obvious that the something will always execute, no matter what (because true is always evaluated to true...)

In your case, you can use the optional chaining operator to make sure the objects exist before accessing properties on them. Your ngIf could look something like this:

 <li class="list-group-item" *ngIf="pedido?.RecursoTerceiraInstancia?.Resposta">

Solution 2:[2]

In Javascript, there's a data type exactly for the purpose of checking if "variable exists": undefined.

So you can do this: typeof pedido.RecursoTerceiraInstancia.Resposta !== 'undefined'

Solution 3:[3]

The quick way

<li class="list-group-item" *ngIf="pedido.RecursoTerceiraInstancia.Resposta">
         <a href="" class="d-flex flex-column align-items-center">
           <span class="icofont-law-order icofont-2x"></span>
           <p>Resposta Definitiva</p>
         </a>
</li>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Octavian Mărculescu
Solution 2 technophyle
Solution 3 Jose Vicente