dave0688
dave0688

Reputation: 5770

Elvis Operator in *ngIf

I know that in previous angular versions an elvis operator did not work in an *ngIf statement. However, now (Angular 6) it doesn't throw an error anymore.

Is this a valid statement?

<div *ngIf="testobject?.sub?.subobj">
    Hallo Test Test
</div>

Whereas

testobj = {}

If so when was it added?

As far as I can remember the statement had to be the following:

<div *ngIf="testobject.sub && testobj.sub.subobj">
    Hallo Test Test
</div>

Can someone please clarify that?

Upvotes: 1

Views: 925

Answers (2)

Suren Srapyan
Suren Srapyan

Reputation: 68645

More correct like this

<div *ngIf="testobject && testobject.sub && testobj.sub.subobj">
    Hallo Test Test
</div>

Says that if testobject is not falsy, then go to it's property with name sub - and if this is also is not falsy, go to the nested property subobj and access its data and evaluate inside *ngIf. If some of the conditions is falsy, return false.

Upvotes: 1

Alf Moh
Alf Moh

Reputation: 7427

To translate the code into plain English will be, if testobject is not null, get sub and if sub is not null get subobj and if testobject and sub and subobj aren't null, output Hallo Test Test. So yeah, the code is valid.

Upvotes: 1

Related Questions