close
close
Expanding/Collapsing All Nodes in Angular 12

Expanding/Collapsing All Nodes in Angular 12

3 min read 09-11-2024
Expanding/Collapsing All Nodes in Angular 12

In Angular 12, creating an interface that allows users to expand or collapse all nodes within a tree structure can significantly enhance user experience. This functionality can be particularly useful in applications that handle hierarchical data, such as file explorers or organizational charts.

Table of Contents

Overview

In this article, we will build a simple tree component that can expand or collapse all of its nodes. We will use Angular's structural directives and property binding to achieve this functionality.

Setting Up Your Angular Project

To get started, ensure you have Angular CLI installed. If not, you can install it globally using the following command:

npm install -g @angular/cli

Next, create a new Angular project:

ng new expand-collapse-demo
cd expand-collapse-demo
ng serve

Once your project is running, you can create the necessary components.

Creating a Tree Component

Create a new component called tree:

ng generate component tree

Now, let's define a basic structure for our tree component in tree.component.ts. We will create a simple model for our nodes:

import { Component } from '@angular/core';

interface TreeNode {
  name: string;
  children?: TreeNode[];
  expanded?: boolean;
}

@Component({
  selector: 'app-tree',
  templateUrl: './tree.component.html',
  styleUrls: ['./tree.component.css']
})
export class TreeComponent {
  treeData: TreeNode[] = [
    {
      name: 'Node 1',
      children: [
        { name: 'Child 1.1' },
        { name: 'Child 1.2', children: [{ name: 'Grandchild 1.2.1' }] },
      ],
    },
    {
      name: 'Node 2',
      children: [
        { name: 'Child 2.1' },
        { name: 'Child 2.2' },
      ],
    },
  ];

  expandAll: boolean = false;

  toggleExpandCollapse() {
    this.expandAll = !this.expandAll;
    this.updateExpandCollapse(this.treeData, this.expandAll);
  }

  private updateExpandCollapse(nodes: TreeNode[], expanded: boolean) {
    nodes.forEach(node => {
      node.expanded = expanded;
      if (node.children) {
        this.updateExpandCollapse(node.children, expanded);
      }
    });
  }
}

Implementing Expand/Collapse Functionality

In the tree.component.html, we will create a structure to display the tree nodes and a button to expand or collapse all nodes:

<button (click)="toggleExpandCollapse()">
  {{ expandAll ? 'Collapse All' : 'Expand All' }}
</button>

<ul>
  <ng-container *ngFor="let node of treeData">
    <li>
      <span (click)="node.expanded = !node.expanded">
        {{ node.name }} 
        <strong *ngIf="node.children">[{{ node.expanded ? '-' : '+' }}]</strong>
      </span>
      <ul *ngIf="node.expanded">
        <ng-container *ngFor="let child of node.children">
          <app-tree-node [node]="child"></app-tree-node>
        </ng-container>
      </ul>
    </li>
  </ng-container>
</ul>

Additionally, create a separate component to handle each tree node. Generate it using the following command:

ng generate component tree-node

In tree-node.component.ts, we will accept a node as an input:

import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-tree-node',
  templateUrl: './tree-node.component.html',
  styleUrls: ['./tree-node.component.css']
})
export class TreeNodeComponent {
  @Input() node!: { name: string; children?: any[]; expanded?: boolean };
}

For the tree-node.component.html, we will display the node name and implement the same expand/collapse logic:

<span (click)="node.expanded = !node.expanded">
  {{ node.name }} 
  <strong *ngIf="node.children">[{{ node.expanded ? '-' : '+' }}]</strong>
</span>
<ul *ngIf="node.expanded">
  <ng-container *ngFor="let child of node.children">
    <app-tree-node [node]="child"></app-tree-node>
  </ng-container>
</ul>

Final Code Example

Once you have set up all the components, ensure your app.component.html includes the tree component:

<app-tree></app-tree>

Conclusion

You have now created a tree component in Angular 12 that supports expanding and collapsing all nodes. This feature not only improves the usability of applications dealing with hierarchical data but also enhances the overall user experience. By utilizing Angular's powerful structural directives, you can easily manage the state of your components and maintain a clean, organized codebase.

Popular Posts