Dynamic List And Sub-List Collapse In Angular

Step1

First follow the below code for HTML in your design page (Ex:component.html).

  1. <div class="brands-name">  
  2.     <div *ngFor="let data of ParentList; let $index=index;">  
  3.         <div (click)="Collaps($index)">Item{{index + 1}}</div>  
  4.         <div *ngIf="$index === expandedIndex">  
  5.             <div *ngFor="let data of ChildList;let i=index">  
  6.                 <div class="row" style="margin-left:0px;margin-right:0px">  
  7.                     <div class="col-sm-1">Sub-Item{{index + 1}}</div>  
  8.                     <div class="col-sm-6" style="width: 80%;"></div>  
  9.                 </div>  
  10.             </div>  
  11.         </div>  
  12.     </div>  
  13. </div>  

Step2

Added component.ts code in your page . This.expandedIndex's  initial value -1 has been assigned as ngOnInit for pageload function. Get ParentList value from database for assigning Header.

  1. constructor(private router: Router, private service: Service) {}  
  2. ngOnInit() {  
  3.     //some values  
  4.     this.expandedIndex = -1  
  5.     this.ParentList = [];  

 

Step3

I have clicked header position and opened ChildList.

  1. Collaps(index: number) {  
  2. this.expandedIndex = index === this.expandedIndex ? -1 : index;  
  3. //some values  
  4. this.ChildList = [];  
  5. });  
  6. }  
  7. (click) = "Collaps($index)"  
The Click event passed Header position index value to assign this expandedIndex value. When user clicks ParentList click postion collapses and opens childlist.

 

 

Finally we have successfully gotten dynamic Collapse in Angular4. I hope this blog was mostly helpful for you.