Search code examples
htmlangularangular-ng-if

angular *ngIf- check if array in specific index null


I want to check if array in specific index is not null this is my code:

    *ngIf="routeService?.selectedPlaces?[index]!=null"

'routeService' is service that the component gets in its constractor and 'selectedPlaces' is array in the service. 'index' is property in the component.

I got this error:

    main.ts:13 Error: Template parse errors:
    Parser Error: Conditional expression routeService?.selectedPlaces?[index]!=null requires all 3 
    expressions at the end of the expression [routeService?.selectedPlaces?[index]!=null] in 
    ng:///PlaceAutocompleteFromDBComponent/template.html@5:29 ("-field class="example-full-width">

How can I check it?


Solution

  • In Typescript the elvis operator syntax is ?. In the second case, you have used only ?, which is not valid. You need to to use

    *ngIf="routeService?.selectedPlaces && routeService.selectedPlaces[index]"