i'm trying to build a treeview in my angular project from a nested data and i want to highlight only the selected item. Here is the stackblitz link what i had tried. https://angular-ivy-wcv63x.stackblitz.io
currently it highlights all the selected items and turns off on isitemSelected == false
please suggest/help, if there are any missing elements in my code.
CodePudding user response:
when we want to "only select one" we use a simple variable and store the value, not use a property of the "item" or an array.
itemSelected:any=null
And use ngClass as
<div (click)="onexpand(item)"
[ngClass]="{'treeViewSelected': item==itemSelected,
'treeViewExpanded': item.isExpanded}">
...
</div>
As the "itemSelected" it's only one, you need the itemSelected belong to "parent". So we are using a itemSelected itemSelectedChange. As we have a recursive element, we need emit also the value to the "parent". So really the itemSelect will be, an @Input
, an @Ouput
and a getter
to emit the value. Some like
_itemSelected: any = null;
@Input('itemSelected') set _(value: any) {
this._itemSelected = value;
}
get itemSelected() {
return this._itemSelected;
}
set itemSelected(value: any) {
this._itemSelected = value;
this.itemSelectedChange.emit(value);
}
@Output() itemSelectedChange: EventEmitter<any> = new EventEmitter<any>();
And change the onexpand using emit
onexpand(item) {
this.itemSelectedChange.emit(item == this.itemSelected ? null : item);
if (item.expanded) {
item.expanded = !item.expanded;
return;
} else {
if (item.children) {
if (item.children.length > 0) {
item.expanded = true;
} else {
item.expanded = false;
}
}
}
}
Now we are using two ways binding.
In app.component
itemSelected:any=null
//and
<app-tree [items]="sampleData" [(itemSelected)]="itemSelected"></app-tree>
In the recursive component
<ul >
<li *ngFor="let item of items">
...
<ul *ngIf="item.children && item.expanded">
<!--here use the two binding too-->
<app-tree [items]="item.children" [(itemSelected)]="itemSelected">
</app-tree>
</ul>
</li>
</ul>
Your forked stackblitz