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

When attempting to print a string from an array, an inaccurate result is

Hi, I could really use some assistance with this issue. The array given to me is structured like this: char **indexArray; I was instructed to add to the array in this way: indexArray[recCount++]=root->data; Although recCount is not crucial, whenever ...

Searching JSON Data for Specific String Value Using JavaScript

I am looking for a straightforward approach to search my JSON string using JavaScript. Below is the PHP code that generates my JSON String: <?php $allnames = array(); $res = mysql_query("SELECT first,last FROM `tbl_names`"); while ($row = mysql_fetch_ ...

Retrieve information from MySQL database to display in Android application

I am trying to retrieve data from a MySQL database using PHP and display it in an Android activity. I have coded it to pass a JSON Array, but I am encountering a problem connecting to the server because my database is located on a local server. Can someone ...

Encountering an Uncaught ReferenceError in Angular 8 and Webpack 4: Issue with vendor_lib not being defined plus source map error

Recently, I started working on a relatively simple interface that was initially developed in Angular2. As someone new to Angular2 and webpack, there were some challenges. I successfully upgraded the project from Angular 2.4 to Angular 8.0. Additionally, ...

Ways to generate arrays in Typescript

My dilemma lies in a generator method I've created that asynchronously adds items to an array, and then yields each item using yield* array at the end of the process. However, TypeScript compiler is throwing me off with an error message (TS2766) that ...

Issue with accessing storage in Ionic Storage (Angular)

Currently, I am attempting to utilize Ionic storage for the purpose of saving and loading an authentication token that is necessary for accessing the backend API in my application. However, I am encountering difficulties retrieving the value from storage. ...

Exploring Inheritance in Java JSON Configuration Files

I am working with an API that retrieves details from a JSON config file. For example: "sections": { "Vehicles": ["Car ", "Bus",], "Air transport": ["Helicopter", "Aeroplanes "] ...

ngClass with multiple conditions

I am currently working on implementing the following functionality - I have two pre-set classes that are combined with some component variables successfully. However, I now need to include an additional conditional class. Although the first part is functi ...

Converting a JSON array of key-value pairs into a Plain Old Java Object (POJO

Is it possible to use Jackson to convert the JSON data below into a POJO class? { "company": [{ "employee": { "address": { "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c7a6a5a487a0aaa6aeabe9 ...

My function won't get called when utilizing Angular

My Angular code is attempting to hide columns of a table using the function shouldHideColumn(). Despite my efforts, I am unable to bind my tags to the <th> and <td> elements. An error keeps popping up saying Can't bind to 'printerColu ...

Create a TypeScript function called toSafeArray that transforms any input into a properly formatted array

Is there a way to create a function that can transform any type into a safe array? toArray(null) // []: [] toArray(undefined) // []: [] toArray([]) // []: [] toArray({}) // [{}]: {}[] toArray(0) // [0]: number[] toArray('') // ['']: str ...

Substitute the symbol combination (][) with a comma within Node.js

Currently, I am utilizing Node JS along with the replace-in-file library for my project. Within a specific file named functions.js, I have implemented various functions. Furthermore, in another file named index.js, I have added code to call these functio ...

Using Angular 2's rxjs switchMap function will produce an Observable<Object> as the

I am currently developing a TypeScript Angular 2 application and utilizing RxJS. I am following the example given in this tutorial: https://angular.io/docs/ts/latest/tutorial/toh-pt6.html#!#stq=formgroup&stp=1 Although I am attempting to strongly typ ...

Running NG BUILD from Gulp can be done using either child-process.spawn or by disabling all output in child-process.exec

Have you come across a similar question like this Call "ng build" from inside a gulp task? I have found a way to successfully build Angular using Gulp in order to prevent overflowing the output buffer. Here's how I achieved it: const child ...

Struggling to implement server side processing with Datatables in MVC4?

Greetings, our current setup involves an MVC4 application that is handling a large number of records with thumbnail images in a jQuery Datatables driven view. Unfortunately, the loading time is slow due to all thumbnails being fetched at once during a GET ...

Combining strings from an array while restricting repeated characters

I have an array of strings that need to be combined to form a single string, using a specific number referred to as the associatedNumber. This associatedNumber dictates that in the final result, all clusters of identical characters (from the array) should ...

Is there a more efficient method for examining each multidimensional array?

I have created a program that converts JSON to PHP and checks every value of a multidimensional array with a foreach loop. If a value meets a certain condition, it deletes that key and value and then converts it back to JSON. I am trying to achieve this wi ...

Searching for a property in JSON using C# can be done by parsing the

Ensuring that every request in our ASP.Net Web API project is logged is a priority. Each request requires a search for a specific property/token (PersonId) within the payload, which must then be stored in the log table. The challenge arises from the fact ...

The "fullName" input remains constant despite any changes made during text input

Currently, I am in the process of implementing a ControlValueAccessor in a child form. In my setup, there is a parent form group and control structured like this: this.form = this.formBuilder.group({ user: ['', Validators.required] ...

Error: Unable to call function onPopState from _platformLocation due to TypeError

After building an angular application, I encountered a strange issue where it runs smoothly in non-production mode but throws an error when running with --prod: Uncaught TypeError: this._platformLocation.onPopState is not a function I have double-checked ...