I’m looping through an API response and displaying some items (female and male age groups) on a page with the following code:
<ng-container *ngFor="let event of day.availableEvents"> {{ event.name }} <br> <ng-container *ngFor="let maleAgeGroup of event.maleAgeGroups"> <span [class.is-active]="status" (click)="updateStatus()" {{ maleAgeGroup }}</span> </ng-container> </ng-container>
And, this the JSON data I’m working with:
"days": [ { "date": "2021-04-14T00:00:00.000Z", "availableEvents": [ { "id": 1, "name": "Event A", "femaleAgeGroups": ["U13", "U15", "U17"], "maleAgeGroups": ["U13", "U15", "U17"] }, { "id": 2, "name": "Event B", "femaleAgeGroups": ["U13", "U15", "U17"], "maleAgeGroups": ["U13", "U15", "U17"] }, ] } ]
On click of an age group I want to toggle its status from true or false so that the is-active
CSS class is add/removed.
No matter what SO answer I try, I can’t get it to work and in most cases end up with an error like ‘Cannot assign status to type string’. This is why I’ve stripped back the above code right to basics – maybe it’s because of the way my data is structured?
The example below is what I’m trying to end up with, where the highlighted text has been clicked and is-active
class applied:
Advertisement
Answer
[class.is-active]
needs to ‘bind’ to a value, it is unclear to me the intent of what you trying to do as a whole, but, each age group needs a state. Thus, you need to update/modify your data either from the server or augment in your component with the status for each age group…
"femaleAgeGroups": [{name:"U13", active:true}, {name:"U15", active:false}, {name:"U17", active:false}], etc..
Then in the template you can bind the css class to the boolean value
<ng-container *ngFor="let maleAgeGroup of event.maleAgeGroups"> <span [class.is-active]="maleAgeGroup.active" (click)="updateStatus(maleAgeGroup)" {{ maleAgeGroup.name }}</span> </ng-container>
.. and to update you pass the item to update function and update its active state:
updateStatus(item:any): void { item.active = !item.active; }