0

I want to add a div on click of button, and it should have 1 did added by default and on newly added div i need a class active on it

 <div class="card-content">
    <div class="questions" *ngFor="let question of questions, let i = index" [ngClass]="{'active': i}">
      <app-question-card></app-question-card>
    </div>
  </div>
  <div class="footer" (click)="addNewQuestion()">
    <div class="running-txt">Add new question</div>
  </div>

questions: number[] = [1];
addNewQuestion() {
    this.questions.push(this.questions.length);
  }

the add is working as expected but the class is not getting appended the way it should and it is not getiing removed from 1 default added div as well any idea?

2
  • If you always want class active appended, just add it as class="active". Your expression [ngClass]="{'active': i} means add class active if i is truthy (meaning the first item will not have it as i is 0 in that case). Commented Mar 27, 2020 at 12:13
  • i want to add active only on the last element added in the questions array by default the question array has one div so active should be on that div and when i click on addNewQuestion() then active should on the lastest added div Commented Mar 27, 2020 at 12:15

1 Answer 1

2

If you want to apply the class active to only the last item, you can do it like this;

<div class="questions" *ngFor="let question of questions; let last = last" [ngClass]="{'active': last}">
  <app-question-card></app-question-card>
</div>

This creates a variable that can be used to identify the last item in the list.

Sign up to request clarification or add additional context in comments.

4 Comments

Glad to help :)
it will be really helpful if u can help me out on how to pass that active class to the <app-question-card></app-question-card> based on ngClass check as input decorator
You can use the same expression for you custom component: <app-question-card [ngClass]="{'active': last}">. You could also create an @input for your component and set it like [isLast]="last". Good luck :)
active class can either be on the last element or recently clicked index... how to manage that?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.