Unleashing the power of dynamic nested lists in Angular 2

I'm facing a challenge with my dynamic list created using ngFor. What I want is to expand the list for a specific item when clicked, instead of expanding all items in the list. The issue is that currently, every item expands when I click on one. I understand why this is happening but struggling to find a solution.

Below is my code snippet:

<ul *ngFor="let p of portList">
    <li (click)="setONUList(p.name)" id="{{ p.name }}"><img src="app/resources/{{ p['oper-status'] }}.png" class="myimage"/>{{ p.name}}</li>
        <ol *ngFor="let onu of portONUList">
            <li><img src="app/resources/{{ onu['oper-status'] }}.png" class="myimage" />{{ onu.name}}</li>
        </ol>
</ul>

I would greatly appreciate any suggestions on how to tackle this problem.

Answer №1

Based on my understanding, the subarray remains constant and is displayed for all items in your list. In this case, there seems to be no direct connection between the nested array and the outer array.

One suggestion I have is to introduce a new property within your main array, such as expanded. This way, your main array could be structured like this:

portList = [{id:1,name:'one',expanded:false},{id:2,name:"two",expanded:false}];

Then, you can implement it in your HTML code as follows:

<ul *ngFor="let p of portList">
  <li (click)="expand(p)">{{ p.name}}</li>
  <div *ngIf="p.expanded">
    <ol *ngFor="let onu of portONUList">
      <li>{{ onu.name}}</li>
    </ol>
  </div>
</ul>

To toggle the expanded property on click, you can use the following function:

expand(p: any) {
   p.expanded = !p.expanded;
}

If you prefer a quicker solution without adding a new property, you can utilize HTML5 features like so:

<details *ngFor="let p of portList">
  <summary>{{p.name}}</summary>
    <ul *ngFor="let onu of portONUList">
      <li>{{ onu.name}}</li>
    </ul>
</details>

You can also view examples of both options in this Plunker demo.

Answer №2

A connection must exist between the parent and the childlist, presented in json format. Below is an example code snippet:

<ul>
        <li ng-repeat="item in parent" ng-click="showChilds(item)">
            <span>{{item.name}}</span>
            <ul>
                <li ng-repeat="subItem in item.subItems" ng-show="item.active">
                    <span>{{subItem.name}}</span>
                </li>
            </ul>
        </li>
    </ul>

JSON FORMAT Example:

let parent= [
        {
            name: "Item1",
            subItems: [
                {name: "SubItem1"},
                {name: "SubItem2"}
            ]
        },
        {
            name: "Item2",
            subItems: [
                {name: "SubItem3"},
                {name: "SubItem4"},
                {name: "SubItem5"}
            ]
        },
        {
            name: "Item3",
            subItems: [
                {name: "SubItem6"}
            ]
        }
    ];

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the capabilities of this class in Jquery attribute manipulation

Presented below is a piece of code written in HTML and jQuery HTML <div id="myForm" class="myForm row"> <div class="form-group row"> <div class="col-lg-12"> <div class="col-md-4"> <label& ...

Styling does not seem to apply to inner components in NEXTJS

I am attempting to create a ChatGPT replica using Next.js and Tailwind CSS. My focus is currently on the main chat screen, where each message is displayed using a separate Message component with its own styling. However, I am facing an issue where the styl ...

Tips for concealing scrollbars across various browsers without compromising functionality

Is there a way to hide the scrollbar functionality on a horizontal scrollbar without using "overflow: hidden"? I need to maintain JS functionality and ensure compatibility with all modern browsers. $j = jQuery.noConflict(); var $panels = $j('#primar ...

What is the purpose of the video-js endcard plugin incorporating native controls into the player?

Endcard is a unique plugin designed for the video-js html5 video player that adds clickable links to the end of a video. (More information on endcards can be found here: https://github.com/theonion/videojs-endcard). To implement an endcard, simply include ...

Preventing Bootstrap 4 slider images from shifting position when using background-attachment:fixed for a parallax effect

I'm trying to implement a Parallax scrolling effect on my Bootstrap 4 slider. However, every time the slider switches to the next image, the image needs to readjust itself into place. How can I avoid this? .customOverlayText { position: absolute; ...

Is ngOnDestroy in Angular 2 triggered on page refresh, or only when navigating away from the component?

Can anyone clarify whether the ngOnDestroy method in Angular 2 is triggered on page refresh or only when navigating away? ...

Is there a way I can finish animating these divs in a diagonal motion?

I successfully made the blue and red divs move diagonally and switch positions. Now I am looking to achieve the same effect with the green and pink divs using a similar function. I am unsure about setting the position of both divs to 0 and 350 for those p ...

Insert PDF to completely fill the screen

Seeking advice on embedding a PDF in an HTML document with a consistent height of 100%. The challenge lies in the varying height of the PDF, and the need for the layout to adapt accordingly. ...

Styling in CSS for aligning a drop-down menu to the right side

I recently incorporated a CSS/JavaScript drop-down menu on my website, which I sourced from the following page: However, I am facing an issue with aligning the far-right drop-down properly. Specifically, I would like the items in the far-right drop-down t ...

Fixed navbar at the top changes from absolute positioning to relative when scrolling

My goal is to dynamically change the position of the navbar from fixed to absolute as the user scrolls past 600px. Initially, I used the following code: if (scroll >= 700) { $(".navbar-fixed-top").addClass("navbar-scroll"); } else { $(".navbar ...

Alignment of headers and footers in email newsletters for various email clients<td>

With my limited coding skills, I've been struggling to keep the header and footer aligned properly in all email clients. The footer consistently displays a 1 px gap between elements, which causes it to move around unpredictably. Here's the full s ...

How can custom selectors be created in LESS?

Let me provide an example of my desired approach. :all() { &, &:link, &:visited, &:active, &:focus } The concept above involves a 'custom selector' that encompasses all pseudo-classes of an anchor tag, e ...

Animated CSS sidemenu (utilized as a filtering panel for a table)

Hi there, I'm having some trouble with CSS Animation. I recently started developing websites and am using Bootstrap 4 along with Animate.css for animations. My goal is to have an icon button expand sideways to reveal a div containing select elements f ...

Tips for eliminating the draggable item's shadow in Angular

Is there a way to remove the shadow seen under the backdrop when dragging an item in the Bootstrap modal dialog? In the image provided, I am trying to drag the "Personal Details" button..https://i.stack.imgur.com/uSNWD.png ...

How can I fix the "element is not defined" error in JavaScript when using Get

Having some issues displaying the #coupon using JavaScript, as I am encountering an error message stating that getElementById is undefined. Code Snippet (HTML) <html> <head> <title>Exercise</title> <link rel="styles ...

Connecting buttons to JavaScript functions that interact with MySQL database entries

I am working on a task involving rendering a database table using XMLHttpRequest in JavaScript to a PHP page. My goal is to display each entry from the table as an HTML row/cell with two buttons within each "entry". These buttons should trigger specific Ja ...

How to Include a JavaScript File from a Local Source on a Web Page

Is the process for adding a script with document.createElement('script') the same when it comes to a local file? I've experimented with using function.toString() calls, but it's not very efficient. I would prefer to store the necessary ...

I wish to have the option to choose a courseId when creating a new hole by clicking the "create new hole

I'm currently developing a golf score tracking application. I have set up a database with tables for Rounds, Courses, and Holes. The Hole table contains a foreign key that links to the CourseId, allowing me to associate each hole with a specific cour ...

Tips for resolving the final item issue in Owl Carousel when using right-to-left (RTL)

Encountering a bug with the rtl setting in owl-carousel. When the rtl is applied to the slider and I reach the last item, the entire slider disappears! Here's the code snippet: var viewportWidth = $("body").innerWidth(); if (viewportWidth & ...

Bootstrap modal with sticky-top class displays abnormal margin and padding upon being shown

Whenever I launch a bootstrap modal, I notice unexpected side padding or margin appearing on certain HTML elements. For instance: Before displaying the modal: <div id="fixedMenu" class="d-none container-fluid menu sticky-top px-0" s ...