[Fixed] Cleanly perform null checks in Angular HTML Template


I’m wondering if there’s a way to shorten the code here:

<td class="value">
    {{nonprofitRating?.financialRating?.performanceMetrics?.fundraisingEfficiency == null || ... == undefined ? ... : 'N/A' }}

to something more clean without adding getters to my .component.ts file. Is there a way to shorten the variable in Angular to something like in the below code block? This is information loaded into an NonprofitRating object from an API fetch call that may or may not be null or undefined, so I would prefer not to have 20 getters or 20 different variables in my .component.ts file for cleanliness purposes.

<td class="value" let fundraisingEfficiency = ...chained undefined check statement...>
    {{fundraisingEfficiency == null || ... == undefined ? fundraisingEfficiency.toFixed(2) : 'N/A' }}


I ended up using ngSwitch to cleanly handle situations where the variable chaining would be too long, and avoid repetition. It also makes it very clean for handling if / else / then statements without mucking up the component.ts file, in my opinion.

<td class="value" [ngSwitch]="nonprofitRating?.accountabilityRating?.accountabilityTests?.materialDiversionOfAssets?.toLowerCase()">
    <mat-icon *ngSwitchCase="'pass'" style="color: green" style="color: green">check_circle_outline</mat-icon>
    <mat-icon *ngSwitchCase="'remediated'">remove_circle_outline</mat-icon>
    <mat-icon *ngSwitchCase="'fail'" style="color: red">cancel</mat-icon>
    <p *ngSwitchDefault>N/A</p>                        

Leave a Reply

(*) Required, Your email will not be published