Set attribute conditionally in angular 4

Viewed 13769

I want to set href attribute of element depend on content of element from interpolation.

<div>
    <ul class="contactnav">
        <li *ngFor="let contactItem of contactItems" >
            <a class="{{ contactItem.iconBootStrap }}"  href=" {{ contactItem.contactForm.indexOf('@') }} !== -1? 'mailto:{{ contactItem.contactForm }}' : '#'" data-rel="external">
                {{ contactItem.contactForm }}
            </a>           
        </li>
    </ul>
</div>

How should I define condition in element to set href for value if contactItem.contactForm includes @ otherwise set for value '#'?

2 Answers

What you ask for is setting a property, not an attribute.

You can use

[href]="contactItem.contactForm.indexOf('@') !== -1 ? 'mailto: ' + contactItem.contactForm : '#'"

For conditional attribute binding see How to add conditional attribute in Angular 2?

Try this,

  <a class="{{ contactItem.iconBootStrap }}" [href]="contactItem.contactForm.indexOf('@') !== -1? 'mailto: ' + contactItem.contactForm : '#'" data-rel="external">
      {{ contactItem.contactForm }}
  </a>       
Related