juhi
juhi

Reputation: 578

dynamically add div to container angular 6

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?

Upvotes: 0

Views: 172

Answers (1)

DaggeJ
DaggeJ

Reputation: 2191

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.

Upvotes: 2

Related Questions