Home > Software engineering >  How to bind in angular conditionally in *ngFor?
How to bind in angular conditionally in *ngFor?

Time:11-12

I have html that looks something like this:

  <as-split unit="pixel" #mainViewSplit  direction="horizontal" gutterSize="2">
    <ng-container *ngFor="let splitItem of splitData">
      <as-split-area [id]="splitItem.id" *ngIf="(splitItem.isVisible$ | async)" 
      [order]="splitItem.order">
      <ng-container *ngTemplateOutlet="splitItem.template"></ng-container>
      </as-split-area>
    </ng-container>
  </as-split>

This works fine for split items that have id. But some of them are undefined and then there shouldn't be id at all in html. But for items without id html looks like this:

id="undefined"

I also tried

[id]="splitItem.id ? splitItem.id : null"

because comment in this question suggest to use null, but it doesn't work. It just results in

id="null"

How to set binding so that there won't be id in html at all?

CodePudding user response:

use [attr.id] in place of [id] if the value of splitItem.id is undefined the attribute id will not be added in the DOM

<as-split-area
  [attr.id]="splitItem.id"
  *ngIf="splitItem.isVisible$ | async"
  [order]="splitItem.order"
>
  <ng-container *ngTemplateOutlet="splitItem.template"></ng-container>
</as-split-area>

CodePudding user response:

Have you tried using index instead of id ? so that instead of undefined you will get a number in property [id].

Follow this:-

*ngFor="let splitItem of splitData; let i = index"

and then in your <as-split-area [id]="i">

CodePudding user response:

You can just set the id as an empty string if it is undefined. Like so

[id]="splitItem.id ? splitItem.id : ''"
  • Related