Home > Mobile >  Displaying component dynamically by index inside ngFor
Displaying component dynamically by index inside ngFor

Time:01-19

I have a bunch of tasks and they have comments, when I click show comments on a particular list element I want to display only the component for that index.

<ul  *ngFor="let item of todayTasks;let i = index">

     <li ..
       <button (click)="displayCommentsComponent(i)">Comments</button>
    </li>
    <app-today-tasks-comments id="{{'tasksComment'   i}}" *ngIf="showCommentComponent"</app-today-tasks-comments> 
</ul>

I don't know what to put in that *ngIf to display one specific element by index, right now it shows all of them.

CodePudding user response:

Update your code to have the *ngIf dependent on the index: *ngIf="showCommentComponent[i]"

<app-today-tasks-comments id="{{'tasksComment'   i}}" *ngIf="showCommentComponent[i]"></app-today-tasks-comments> 

And then in your class, toggle that index on a map:

showCommentComponent = {};

displayCommentsComponent(index){
  this.showCommentComponent[index] = !this.showCommentComponent[index];
}
  •  Tags:  
  • Related