'How can expand and a particular div by clicking a +/- icon in angular2?
I want to have + icon to expand and - collapse a particular div. I have Array of objrcts so i'll iterate using *ngFor="let data of dataArray"
I have the example to achieve this using accordion. But i want to open all the div when i click + and close the particulat div when I click "-" icon of the particular div. But accordion will open only one at a time
I want to have something like below
- data[0].name
{{data[0].categoryName}} , {{data[0].groupName}}
- data[1].name
{{data[1].categoryName}} , {{data[1].groupName}}
+ data[2].name
+ data[3].name
- data[4].name
{{data[4].categoryName}} , {{data[4].groupName}}
I want to open it in Top-Down and also need a scroll bar when the content is big
Solution 1:[1]
The most basic form of what you want can be created this way.
You can always add more css and styles to make it look the way you want.
ts:
import {Component} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
@Component({
selector: 'my-app',
template: `
<div>
<div class="div" *ngFor="let data of dataArray; let i = index" (click)="iconChange(i)" style="margin-bottom: 20px">
<div>
<i class="fa" [ngClass]="{'fa-plus': flagArray[i] == false, 'fa-minus': flagArray[i] == true}" aria-hidden="true" style="float: left"></i>
{{data.name}}
</div>
<div *ngIf="flagArray[i] == true" class="div2">
{{data.categoryName}} - {{data.groupName}}
</div>
</div>
<button (click)="showAll()">Expand All</button>
<button (click)="hideAll()">Collapse All</button>
</div>
`,
stylesUrl:['./style.css']
})
export class App {
flagArray = [];
dataArray = [];
selectedIndex: number;
constructor() {
this.selectedIndex = -1;
this.dataArray = [
{name: '1', categoryName: 'A1', groupName: 'G1'},
{name: '2', categoryName: 'A2', groupName: 'g2'},
{name: '3', categoryName: 'A3', groupName: 'G3'},
{name: '4', categoryName: 'A4', groupName: 'G4'}
]
for(let i=0; i<this.dataArray.length; i++){
this.flagArray.push(false);
}
}
iconChange(i: number){
this.flagArray[i] = !this.flagArray[i];
}
showAll(){
for(let i=0; i<this.dataArray.length; i++){
this.flagArray[i] = true;
}
}
hideAll(){
for(let i=0; i<this.dataArray.length; i++){
this.flagArray[i] = false;
}
}
}
Solution 2:[2]
Angular Boostrap collapse component
*ngIf to make your own collapsible html or bind a [hidden] if you want to pre-load and keep the DOM while not displayed. You can then use angular animation modules to add an animation.
Solution 3:[3]
While implementing this yourself would probably be interesting, if you're looking to save on work, there's an app component library for that!
https://github.com/500tech/angular-tree-component
or
https://github.com/valor-software/ng2-tree
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | snaplemouton |
| Solution 3 | LarsMonty |
