Reputation: 1126
In Angular you can use ngClass to conditionally apply your class like so.
<div
*ngFor="let group of step.groups; let firstItem = first;"
class="layout--stepper__subgroup"
ngClass]="{'is-active': group.prop === activeProp}"
(click)="scrollToSection(group)">
p class="t-data">{{group.header}}</p>
</div>
scrollToSection(group) {
this.activeProp = group.prop;
let scroll = document.querySelector(`#${group.prop}`).scrollIntoView();
}
Now whenever I click the item in my list the class is-active
will be applied to that specific list item. However, what if I want to apply is-active
to the first item on the list by default?
If I change my code to be:
ngClass]="{'is-active': group.prop === activeProp || firstItem}"
Now both the first item on the list and the item clicked will both have the is-active
class. How can I set the first item on the list to have the is-active
class by default and then remove it when I click another item on the list?
Upvotes: 1
Views: 1185
Reputation: 8660
If you are aware of the value of prop
for your firstItem
, the easiest way to do it would be to set activeProp
initially to that value.
In case the value is not known to you, try setting is-active
to your firstItem
only if activeProp
is not defined which would be when no item is selected.
[ngClass]="{'is-active': group.prop === activeProp || (firstItem && !activeProp)}"
Upvotes: 1
Reputation: 1040
Initialize the activeProp as the prop of the first group of the groups array:
if(this.step.groups.length > 0)
this.activeProp = this.step.groups[0].prop;
And your first condition:
[ngClass]="{'is-active': group.prop === activeProp}"
will run smoothly.
Upvotes: 0