Reputation: 3117
I´m quite new to Angular 2 and I want to assign a class to an HTML-Element. It should be dynamic --> If another element (with an id) has an attribute, this element should become the class.
Here´s my code I tried:
<div class="panel panel-default" ngFor="let date of epgDates; let i = index">
<div class="panel-heading" role="tab">
<h4 class="panel-title">
<a #aEle role="button" data-toggle="collapse" id="a-{{i}}" href="#{{i}}" aria-expanded="true">
<span class="glyphicon" [class.glyphicon-minus]="aEle.getAttribute('aria-expanded')==='true'"
aria-hidden="true">
</span> {{date | date: 'dd.MM.yyyy'}}
</a>
</h4>
</div>
</div>
With this code i get an error... :/ Can someone help me here?
Thanks so much!
Upvotes: 2
Views: 1442
Reputation: 658253
You can't use []
and {{}}
together. Either one or the other but not both
This sets the class when "true"
is an expression that returns true
otherwise the class is removed
[class.glyphicon-minus]="true"
This sets a class glyphicon-minus
when the expression true
returns true
otherwise the class is removed and sets or removes the class #a-1.aria-expanded
when the 2nd expression returns true
otherwise removes it (assuming i
is 1
).
The class name can be a string ('glyphicon-minus'
) or an expression ('#a-' + i + '.aria-expanded'
)
[ngClass]="{'glyphicon-minus': true, '#a-' + i + '.aria-expanded': true}"
The expression true
and be a literal boolean value (as shown) or the name of a property of the component class, or a more complicated expression with operators and function calls.
update
<a #aEle role="button" data-toggle="collapse" id="a-{{i}}" href="#{{i}}" aria-expanded="true">
<span class="glyphicon" [class.glyphicon-minus]="aEle.getAttribute('aria-expanded')==='true'" aria-hidden="true"></span>
{{date | date: 'dd.MM.yyyy'}}
</a>
I added the #aEle
template attribute to <a>
and use it to get the aria-expanded
attribute value.
Upvotes: 3