Search code examples
htmlcssangularngforangular-ng-if

How to add id to element in ngfor and conditional creation of element in ngfor


I would like to use an ngfor to build for each element in the loop one div, with 3 inner divs. These three inner divs have each a span that displays some text from the element (the element is just a json series of key value pairs, and the content of each span is the value of a given key).

I would like to do 2 things:

  1. Give an id to the outer div based on the index in the ngfor plus some string. I couldnt get it to work (see below) by using

    [attr.id]="element-i"

  2. Only create one of the divs if the element has a value for the given key (See below) with

*ngIf="{{element.key3!=null}}"

This is my code attempt

  <div *ngFor="let element of data; index as i" [attr.id]="element-i">
      <div><span><b>Element number {{element.key1}}</b></span></div>
      <div><span><b>Elmenent value 2:</b>{{element.key2}}</span></div>         
      <div *ngIf="{{element.key3!=null}}"><span><b>Element value 3:</b>{{element.key3}}</span></div>
   </div>

Is this possible to do in angular 5?


Solution

    1. If you don't add single quotes, angular tries to evaluate the element-i expression, which is not valid

    Try this

    <div *ngFor="let element of data; index as i" [attr.id]="'element-'+i">
    
    1. when using *ngIf, you don't need the {{, it's expecting an expression

    Try that

    <div *ngIf="element.key3!=null"><span><b>Element value 3:</b>{{element.key3}}</span></div>