BBaysinger
BBaysinger

Reputation: 6987

Angular 2 *ngIf condition body still rendering when condition is false

I have a loop in an Angular 2 template that is giving me an error because my service, _adfService, is apparently null (even though it logs as non-null prior to any error.) Just to try to get it working, I wrapped it in an if statement to see if I could prevent the loop from rendering whenever _adfService happens to be null. I still get the same error:

Cannot read property 'grids' of undefined

Why can't I prevent the loop from causing an error if Angular 2 is supposedly not rendering the body of the condition?

    <span *ngIf="_adfService != null">
      <li *ngFor="let grid of _adfService.grids" router-active>
        <a class="navlink" [routerLink]="['group/1/grid/']">Grid 1</a>
      </li>
    </span>

Upvotes: 1

Views: 3520

Answers (1)

ablopez
ablopez

Reputation: 850

That's because you're evaluating for null in the *ngIf, which is a totally different value than undefined in Javascript/TypeScript.

To fix it, just change the *ngIf to this:

<span *ngIf="_adfService">

That will evaluate if the _adfService variable evaluatues to "true" (that is, is not undefined, not null, not false, not zero, and not an empty string) and thus not render the *ngFor if the variable is not initialized with the object you're trying to use.

Upvotes: 1

Related Questions