select only parent node treeview in angular 4

2.5k Views Asked by At

i am working with ngx-treeview in angular 4. here i want only parent need to be select when i click on it.Picture so, how to achieve it

<ng-template #itemTemplate let-item="item" let-onCollapseExpand="onCollapseExpand" let-onCheckedChange="onCheckedChange">
<div class="form-check">
    <i *ngIf="item.children" (click)="onCollapseExpand()" aria-hidden="true" class="fa" [class.fa-caret-right]="item.collapsed"
        [class.fa-caret-down]="!item.collapsed"></i>
    <label class="form-check-label">
        <input type="checkbox" class="form-check-input" id="TreeViewCheckBox" value={{item.value}}
            [(ngModel)]="item.checked" (ngModelChange)="onCheckedChange()" [disabled]="item.disabled" (click)="treeviewSelectedValues($event)" />

        {{item.text}}
    </label>
</div></ng-template>
<ngx-treeview [config]="config" [items]="items" [itemTemplate]="itemTemplate">

1

There are 1 best solutions below

0
On

You can do this by extending the TreeviewItem component

For example I submitted a PR to have this functionality but it is not very active. Here is a way to work around it.

import { TreeviewItem, TreeItem } from 'ngx-treeview';


export class CustomTreeviewItem extends TreeviewItem {
constructor(item: TreeItem, autoCorrectChecked?: boolean) {
super(item, autoCorrectChecked);
}

getSelection() {
const items = super.getSelection();
if (this.checked && this.children) {
items['checkedItems'].push(this);
} else {
items['uncheckedItems'].push(this);
}
return items;
}
}

Now you can import your custom component as the TreeviewItem in all files where you use it and no more changes necessary

I also have a way of changing what is returned when item selected. Currently it sends an array of an id of selected item. Perhaps the actual object is more workable. To do that you must do the following

@Injectable()
export class CustomTreeViewEventParser extends TreeviewEventParser {
getSelectedChange(component: TreeviewComponent): any[] {
const checkedItems = this.getCheckedItems(component.items);
return checkedItems;
}

getCheckedItems(items: Array<TreeviewItem>) {
let array = new Array();
if (!items) {
  return array;
}

items.forEach(element => {
  if (element.checked) {
    array.push(element.value);// Here you can push anything you want - element for example. This is then what is emited on selectedChange
  }
});
return array;

}
}
export const treeviewEventParser = {provide: TreeviewEventParser, useClass: 
CustomTreeViewEventParser};

Now in whatever module you import the module- you can provide this parser instead using the providers array and using the custom class