Reputation: 3550
I find myself writing code like this:
<div *ngIf="globals.fieldErrors[item.jsonParent][item.jsonName].locationADiff != null">
<span [ngStyle]="globals.fieldErrors[item.jsonParent][item.jsonName].locationADiff.street1Style" *ngIf="globals.fieldErrors[item.jsonParent][item.jsonName].locationADiff.street1.length > 0">{{globals.fieldErrors[item.jsonParent][item.jsonName].locationADiff.street1}}<br /></span>
<span *ngIf="globals.fieldErrors[item.jsonParent][item.jsonName].locationADiff.street2.length > 0">{{globals.fieldErrors[item.jsonParent][item.jsonName].locationADiff.street2}}<br /></span>
<span *ngIf="globals.fieldErrors[item.jsonParent][item.jsonName].locationADiff.city.length > 0">{{globals.fieldErrors[item.jsonParent][item.jsonName].locationADiff.city}},</span>
<span *ngIf="globals.fieldErrors[item.jsonParent][item.jsonName].locationADiff.state.length > 0">{{globals.fieldErrors[item.jsonParent][item.jsonName].locationADiff.state}},</span>
<span *ngIf="globals.fieldErrors[item.jsonParent][item.jsonName].locationADiff.zip.length > 0">,{{globals.fieldErrors[item.jsonParent][item.jsonName].locationADiff.zip}}</span>
</div>
Is there a way to simplify that? I'd like to set a single variable, such as "myVar" equal to "globals.fieldErrors[item.jsonparent][item.jsonName]" to reduce verbosity.
Upvotes: 0
Views: 46
Reputation: 58523
You can use it like :
<div *ngIf="{ a: 1, b: 2 }; let variable">
<span>{{variable.a}}</span>
<span>{{variable.b}}</span>
</div>
For more detail read : How to declare a variable in a template in Angular2
Answer to your comment is :
Cool, thanks. It works, but means I need a separate with its own *ngIf to test if locationADiff != null. Then another inner that creates the variable. Any idea if there is a way to combine both the test and variable creation into a single *ngIf?
<div *ngIf="checkCondition && { a: 1, b: 2 }; let variable">
<span>{{variable.a}}</span>
<span>{{variable.b}}</span>
</div>
Upvotes: 1