Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 527
maciejka Avatar asked Nov 07 '17 09:11

maciejka


People also ask

How to add attribute on condition in Angular?

This can be done by adding disabled attribute to the nominee name input box when add nominee checkbox is checked. Angular provides support to add an attribute to an HTML element conditionally using the ternary operator.

How to set attribute in Angular?

It would actually need to be "attr. spellcheck" : "true" , and it's just the alternative syntax to @HostBinding() . Everything you can do with Angular decorators, @Input() , @Output() , @ViewChild() , @HostListener() , ..., can be done with host: as well.

How to bind data attribute in Angular?

We simply use attribute binding to add and set a value for a data attribute. According to Angular docs: Attribute binding syntax resembles property binding. Instead of an element property between brackets, start with the prefix attr, followed by a dot (.)

What is attribute and property binding?

Attribute binding syntax is like property binding. In property binding, we only specify the element between brackets. But in the case of attribute binding, it starts with the prefix attar, followed by a dot (.), and the name of the attribute.


1 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?

like image 81
Günter Zöchbauer Avatar answered Oct 13 '22 20:10

Günter Zöchbauer