nativescriptradlistview

How to Expand only one item in collapsible list with NativeScript


I have built a RadListview with nativescript. But now I want that if I tap on an item then only that item should open and other Expanded items should close. I followed this Creating a collapsible list with NativeScript and it works, I just need one item expanding at a time enter image description here

thank you

export class RoadComponent {
    public roads: Array<any>;

    constructor(private page:Page,private router: Router, private roadService: RoadService,private back:BackendService) {
    }
  
    async ngOnInit() {
        this.roads = await this.roadService.getRoads();
    }
   
      templateSelector(item: any, index: number, items: any): string {
        return item.expanded ? "expanded" : "default";
      }
      
      onItemTap(event: ListViewEventData) {
        var listView = event.object as RadListView,
            rowIndex = event.index,
            dataItem = event.view.bindingContext;
            dataItem.expanded = !dataItem.expanded;           listView.androidListView.getAdapter().notifyItemChanged(rowIndex);

      }
      
      }
<Page>
    <StackLayout>
            <RadListView multipleSelection="false" id="abc" height="100%" [items]="roads" [itemTemplateSelector]="templateSelector" class="list-group" (itemTap)="onItemTap($event)">
              <ng-template tkListItemTemplate let-item="item">
              <StackLayout  id="abc" orientation="vertical">
             <Label text="{{item.name}}" class="list-group-item">
                </Label>       
             </StackLayout> 
          </ng-template>
          <ng-template   tkTemplateKey="expanded" let-item="item">
            <GridLayout  rows="auto,auto" columns="*,*" class="list-group-item add-dropdown">
              <Label   row="0" col="0" text="{{item.name}}" class="list-group-item"></Label>
              <Button  row="1" col="0" text="{{item.id}}" (tap)="navigatetomap(item.name)" [nsRouterLink]="['/accueil', { outlets: { homeoutlet: ['home'] } }]"></Button>
              <Button  row="1" col="1" text="{{item.name}}"></Button>
            </GridLayout>

        </ng-template>
        </RadListView>
      </StackLayout>
</Page> 


Solution

  • if anyone had this issue just make expanded property false to all the items

    onItemTap(event: ListViewEventData) {
        for(let i=0;i<this.roads.length;i++){    
            this.roads[i].expanded=false;
        }
        var listView = event.object as RadListView,
            rowIndex = event.index,
            dataItem = event.view.bindingContext;
            dataItem.expanded = !dataItem.expanded;
           listView.androidListView.getAdapter().notifyItemChanged(rowIndex);
    
      }