Search code examples
angularionic3angular-ng-if

Ionic ng-if generates error - ionic 3


I am trying to implement product categories in ionic application as received from the api. but while implementing the same i get the following error

Error: Template parse errors:
Can't bind to 'ng-if' since it isn't a known property of 'div'."

Here is the code:

  <div class="width50" *ngFor="let object of dataList">
    <div *ng-if= "{{object?.categories[0]?.slug}} == single">
    <img src="{{object.images[0].src}}" width="150"  (click)="navigateToPage(object.id)" />
    </div>
  </div>

When i printed the value for {{object?.categories[0]?.slug}} the code worked fine and returned single.

using *ngif over *ng-if also does not seem to work it shows the following error.

`Template parse errors:
TypeError: key[0] is undefined ("
<ion-content padding>
  <div class="width50" *ngFor="let object of dataList">
    <div [ERROR ->]*ngIf= "{{object?.categories[0]?.slug}} == single">
    <img src="{{object.images[0].src}}" width="15"): ng:///AppModule/SinglePage.html@21:9
Can't bind to '*ngIf' since it isn't a known property of 'div'. "`

I believe that this might happen because maybe not all objects have values is the category array. So is there a way to ensure that the *ng-if= "{{object?.categories[0]?.slug}} == single" condition is checked only after ensuring that the category array is non-empty? also can we have both the conditions and loop on the same div ?


Solution

  • You made a type mistake it should be "*ngIf" not "ng-if",

    replace this line,

    <div *ng-if= "{{object?.categories[0]?.slug}} == single">
    

    with

    <div *ngIf= "object?.categories[0]?.slug == single">
    

    problem is that you are trying to interpolate object?.categories[0]?.slug as a string inside your *ngIf condition. Remove the curly braces {{}} and your code will run fine