0

I have a list of elements which looks like :

 <ul *ngFor="let period of periodsDate">
        <li                         
        [class.show]="isShown" (click)="toggleClass()">
        <a>{{ period.id }} </a>
        </li>
</ul>

I add/remove the 'show' class by using the following method:

toggleClass() {
        this.isShown = !this.isShown;
    }

The problem I have is that since there are multiple <li> elements, every time I click on any of them the 'show' class is added to all of them. What I want to achieve is that the class 'show' is only added to the <li> element that was just clicked.

1
  • period.isShown = !period.isShown (passing period as an argument into toggleClass) Commented May 17, 2017 at 13:05

1 Answer 1

0

Use with object period, do not create another object try below code

<ul *ngFor="let period of periodsDate">
    <li class="dropdown__nested" [class.show]="period.isShown" (click)="toggleClass(period)">
        <a>{{ period.key }} </a>
    </li>
</ul>

Typscript

toggleClass(period) {
    period.isShown = !period.isShown;
}
Sign up to request clarification or add additional context in comments.

3 Comments

This works but why would I need to extend period? It seems redundant
did you create class for period? if yes, you can add isShown:boolean in that class.
@greatTeacherOnizuka: because you're in a for loop, the toccleClass function argument has to be something, else how can you guess which of the periodsDates you have to change? there are two ways to handle this: 1) the way Sanjay provided: use a toggleClass function, pass to it the reference to an element and toggle a property. 2) extend the "period" object by adding a function that toggles the isShown variable. Both are good, but the second one, to me, is cleaner. Beware: the this in your toggleClass() function is NOT the this you are expecting.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.