简体   繁体   中英

Set attribute conditionally in angular 4

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 '#'?

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>       

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM