Home > Net >  if else condition inside for loop using angular
if else condition inside for loop using angular

Time:05-26

I am working on a task where I am looping an array inside a tag & using target="_blank" attribute but one of the array element should not want this target="_blank" attribute so what to do?

<ul *ngIf="item.menu">
            <li *ngFor="let subMenu of item.menu">
              <a href="{{subMenu.link}}" target="_blank">{{'landing.menu.'   subMenu.name | translate}}</a>
            </li>
          </ul>

CodePudding user response:

You can use [target] around any tag property to add JS/TS code to it.

 <a href="{{subMenu.link}}" [target]="condition ? '_blank' :'other target type'">{{'landing.menu.'   subMenu.name | translate}}</a>

Other target type list: https://www.w3schools.com/tags/att_a_target.asp

CodePudding user response:

You can add targe attr conditionally by [attr.target]

<ul *ngIf="item.menu">
  <li *ngFor="let subMenu of item.menu">
    <a href="{{subMenu.link}}" [attr.target]="subMenu.link ? '_blank': null">{{'landing.menu.'   subMenu.name }}</a>
  </li>
</ul>

You can test here

  • Related