Filter out all elements in an array except for one from a JSON response using Angular 2

After receiving a JSON response from a server via HTTP GET, the data structure looks like this:

{
    searchType: "search_1",
    overview: [
                "Bed",
                "BedSheets",
                "BedLinen",
                 ..
              ]
}

The contents of the overview array vary depending on the keyword.

To keep track of searched keywords and their responses, I have an Array named Output, structured like this:

[
    {kw: keyword1, resp: {JSON response as mentioned above}},
    {kw: keyword2, resp: {another JSON response with different elements in the `overview` array}}
]

In my component.html file, I aim to display the entries within the overview array as Buttons.

<ul>
  <li *ngFor="let eachOutput of Output">
    <div *ngFor="let each of eachOutput.resp.overview">
      <button *ngIf="eachOutput.resp.overview.length >=1">{{each}}</button>
    </div> <!-- I want to show only the first element here -->
    <!--- Then I want to display additional elements with an option like 'More'
      next to the first button -->
  </li>
</ul>

At present, there are keywords where the array contains numerous elements. I would prefer to display just overview[0] as a button, along with text such as More Options which, when clicked, reveals the other elements of overview.

How should I correctly utilize ngFor and ngIf in this scenario? I've been advised against using the hidden CSS attribute in Angular 2.

Answer №1

To distinguish the first element within the *ngFor loops, you can utilize the index. By using an array of booleans, you can keep track of which buttons should be displayed.

component.ts (implements OnInit)

(...)
@Input() Output: any[] = [];
showMore: boolean[] = [];

ngOnInit() {
  this.showMore = new Array(this.Output.length);
  this.showMore.fill(false);
}
(...)

component.html

<ul>
  <li *ngFor="let eachOutput of Output; let outerIndex = index">
    <div *ngFor="let each of eachOutput.resp.overview; let index = index">
      <button *ngIf="index === 0 || showMore[outerIndex]">{{each}}</button>
    </div>
    <button *ngIf="eachOutput.resp.overview.length > 1" 
      (click)="showMore[outerIndex]=!showMore[outerIndex]">
        {{showMore[outerIndex] ? 'Hide' : 'Show'}} more Buttons
    </button>
  </li>
</ul>

Answer №2

In order to maintain simplicity in my templates, I opt for a different approach when dealing with complex logic - I suggest breaking down response objects into a primary object and an array of secondary objects. These secondary objects can be displayed based on a flag value.

By structuring your template this way, it not only makes coding easier but also enhances readability and comprehension for anyone working on your code.

This concept could be implemented as follows:

[
 {kw: keyword1, response: {primaryResponse: 'Bed', secondaryItems: {bedlinen, pillows}},
 {kw: keyword2, response: {primaryResponse: 'Door', secondaryItems: {window, handle}}
]

<ul>
  <li *ngFor="let eachOutput of Output">
    <button *ngIf="eachOutput.response.primaryResponse">
      {{eachOutput.response.primaryResponse}}</button>

    <button (click)="ToggleSecondaryItems()">More</button>

    <div *ngIf="showSecondaryItems">
      <div *ngFor="let each of eachOutput.response.secondaryItems">
        <button *ngIf="each.overview.length > 0">{{each}}</button>
      </div>
    <//div>    
  </li>
</ul>

*Please note that the code has not been tested, so there may be errors present. However, it should illustrate the basic concept effectively.

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 magic of Spring MVC with the power of Ajax

Is it possible to utilize Ajax in Spring MVC without using <mvc:annotation-driven/>? If yes, then how would I map my controller in app-servlet.xml? I've come across numerous examples with annotations but nothing without them :( Thank you. ...

Work with Dart Language to Parse a Nested JSON Array and Store it in a Model Class

In regards to my inquiry here I am seeking a solution to extract and parse a JSON array without a key nested within another JSON array, and then store it in a Model class. Below is the JSON Array that requires parsing: [ { "pk": 100, ...

What steps can be taken to prevent the browser from freezing when loading JSON via an ajax request?

Hello, I'm currently facing an issue where the dropdown and browser become locked until the ajax request is completed. I've learned that setting ASYNC to False for JSON Ajax requests should prevent this issue. Can someone please assist me in adju ...

Enhancing Json_Encode output with extra arrays

I'm facing some challenges with the json_encode output. To enhance the speed of our extensive dropdown navigation menu, I decided to store all the data in a json file that is updated daily and retrieved as needed. When generating the json using json_ ...

The error thrown is: ProgrammingError - (psycopg2.errors.UndefinedObject) "json" type is not found

I need help uploading a pandas table with a json column into redshift. Here is a simplified version of my code: from sqlalchemy import create_engine from sqlalchemy.types import JSON import pandas as pd RS_creds = {} RS_creds['host'] = %env RS_ ...

What steps can be taken to resolve the 400 Bad status error?

Displayed below is the error along with the output of cfdump, https://i.stack.imgur.com/5LiwO.png This is the JSON Response provided: { "properties": [{ "property": "email", "value": "<a href="/cdn-cgi/l/email-protection" class="__cf_email_ ...

Breaking up an array in PHP according to search outcomes

My dataset consists of a multidimensional array generated from a MySQL query that aggregates results by various groups and sums. The array details costtotal and hitcount for different variations of 'ad_type', 'click_status', and 'l ...

Disable Styling and Override Readonly CSS restrictions

What is the correct approach for customizing material design styling when input fields are disabled? Out of the Box Explore Angular Material Input Examples I managed to achieve my objective using the following CSS, but I am concerned if this is a recomm ...

Encountering issues with deserializing a JSON instance while attempting to parse a JSON file using Jackson

The data I have is stored in a Json file: [ { "name":"Move", "$$hashKey":"object:79", "time":11.32818, "endTime":18.615535 }, { "name":"First Red Flash", "$$hashKey":"object:77", "time":15.749153 }, { ...

Creating a unique object by dynamically incorporating features from another object

I've recently implemented a tree structure in my UI using Material Tree, and it requires creating a new object to represent the tree. The initial object format is as follows: [ { name: 'Fruit', children: [ {name: 'Apple& ...

Unable to retrieve the value of a particular index within an array containing JSON data

Code to add items to an array: var allItems = []; $.getJSON(url, function(data) { $.each(data, function(i) { allItems.push({ theTeam: data[i]["TeamName"], thePlayer: data[i]["TeamPlayer"], }); }); }) When u ...

Incorporating the non-typescript npm package "pondjs" into Meteor applications using typescript files

Implementing the Pondjs library into my project seemed straightforward at first: meteor npm install --save pondjs However, I'm encountering difficulties when trying to integrate it with my Typescript files. The documentation suggests: In order ...

The Angular custom modal service is malfunctioning as the component is not getting the necessary updates

As I develop a service in Angular to display components inside a modal, I have encountered an issue. After injecting the component content into the modal and adding it to the page's HTML, the functionality within the component seems to be affected. F ...

Dealing with Unresponsive Commands in Discord.NET (C#)

I am currently working on developing a discord bot using discord.net that has the capability to fetch all variant Ids from an online store and then sends out discord messages with the variants listed in a specific format: var1 var2 var3 etc During my test ...

best method for implementing a TypeScript object

I've been searching high and low, but I can't seem to find the exact answer I need. Please inform me if my question has already been asked. My goal is to construct an object in TypeScript that includes attributes of custom types. The issue I&ap ...

Retrieving specific information from the Model and returning it as a JSON response using annotations

I am interested in receiving a JSON response with additional annotations. Currently, my JSON response looks like: { "id": 1, "startDate": [ 1993, 12, 12 ], "endDate": [ 2018, 11, 22 ], "totalDistance": 255, "totalPrice": 211 } How ...

Populate a dropdown menu in jQuery with options generated from an array

I'm planning to include 4 dropdowns in my project. My approach involves creating 3 arrays (the first dropdown is hardcoded). The idea is that based on the selection made in the first array, the options for the second dropdown will be populated. How ca ...

What steps are needed to convert this JSON object into a JSON array for easy consumption by Volley?

Trying to retrieve the data from the record using JSON with Volley, but it is not in JSONArray format. How can I modify it to make use of it like this: JsonArrayRequest movieReq = new JsonArrayRequest(url, new Response.Listener<JSONArray> ...

Discovering Spring Boot Properties Within Angular Application

Situation: One microservice is built using Spring Boot and Angular 8. In the Spring Boot application, there is a properties file called application.yaml with the following content: url-header: http gateway: host: envHost:envPort ui-endpoints: g ...

Runtime not able to identify new modifications post migration from Angular 2 to Angular 6

I successfully upgraded my Angular 2 project with DotNetCore to Angular 6 by executing the following command: npm install -g npm-check-updates ncu -u After completing the migration process, I found that while I can still run my previously developed proje ...