Issue
I'm learning NgRx and I need to substitute this template code:
<ion-button *ngIf="myVar.length > 0" ... >
for a code that get the value from a state observer:
myVar$: Observable<string> = this.store.select(mySelector);
so I googled a bit and found lots of examples to do it like this:
<ion-button *ngIf="(myVar$ | async)?.length > 0" ... >
But then I get this compilation error:
[ng] Error: src/app/myModule/myPage.page.html:25:26 - error TS2532: Object is possibly 'undefined'.
There is loads of examples to do it this way in the internet. Why mine doesn't work ? Is this some kind of "old form of coding" that should be modernized ? What is the right way now ?
Solution
This error is thrown because you're trying to access the length property of an object that might be undefined.
You can use the Angular safe navigation operator (?):
<ion-button *ngIf="(myVar$ | async)?.length > 0" ... >
This syntax is correct, however, TypeScript's strict null checking might still throw an error because it doesn't guarantee that length will always be present.
To address the TypeScript error, you can add a non-null assertion (!) after length:
<ion-button *ngIf="(myVar$ | async)?.length! > 0" ... >
Answered By - Aria Noorghorbani
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.