Show array elements in Angular framework

I need help with displaying a list that contains three columns: menu, menuItem, and order.

The desired display format is to show menu and menuItem ordered by order as follows:

Menu 1 : order 200
Menu 2 : order 230
Menu 3 : order 250 
Menu item 1 : order 210
Menu item 2 : order 360

This would result in:

  • Menu 1 has menu item 1 (200 < 210 < 230)
  • Menu 2 : does not have a menu item
  • Menu 3 has menu item 2 (because 250 < 360).

I attempted this by using two lists, one for the menu and another for the menu items. I then tried to save the items falling between the indexes of two menus in a new list for display. However, I am facing an issue with accurately displaying the values for every menu.

Could anyone provide assistance on this matter?

For(I=0; I< list1.length ;I++){
 let nextMenu = list1.order[I+1];
 for (j=0;j<list2.length ;j++){
  let item = list2[j].order;
  let menu = list1[I].order;
 if(menu < item < Next menu){
 This.list3.push(list2[j]);
  }
}
}

Answer №1

To handle the last item differently, follow this approach:

For example, consider refactoring the code as shown below:

(Here is a link to a StackBlitz with the code for testing)

...
// adding attribute class for the lists
  list1 = [];
  list2 = [];
  list3 = [];

const list1 = [
      { menu: 1, order: 200 },
      { menu: 2, order: 230 },
      { menu: 3, order: 250 },
    ];

    const list2 = [
      { item: 1, order: 210 },
      { item: 2, order: 360 },
    ];

    let list3 = [];

    for (let i = 0; i < list1.length; i++) {
      const next = i + 1;

      if (next <= list1.length - 1) {

        let nextMenu = list1[next].order;

        for (let j = 0; j < list2.length; j++) {

          let item = list2[j].order;
          let menu = list1[i].order;

          if (menu < item && item < nextMenu) {
            list3.push(list2[j]);
          }
        }
      } else {

        for (let j = 0; j < list2.length; j++) {

          let item = list2[j].order;
          let menu = list1[i].order;

          if (menu < item) {
            list3.push(list2[j]);
          }
        }

      }
    }

    this.list1 = list1;
    this.list2 = list2;
    this.list3 = list3;
  }

HTML:

<ul>
  <li *ngFor="let menu of list1">
    {{ 'Menu ' + menu.menu + ' : order  ' + menu.order }}
  </li>
  <li *ngFor="let item of list3">
    {{ 'Menu item ' + item.item + ' : order  ' + item.order }}
  </li>
</ul>

UPDATE: Since you mentioned uncertainty about displaying the result in your HTML, I have included the HTML code (with additional attributes for clarity), showcasing the desired outcome, visible in this image:

https://i.sstatic.net/nQ99g.png

I have also updated the StackBlitz.

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

I am interested in utilizing Template literal types to symbolize placeholders

Currently, I am in the process of converting existing javascript files into typescript for my business needs. Below is an example object structure: [ { // Sample column names givenName, familyName, and picture are provided as examples. "giv ...

The error occurred in Commands.ts for Cypress, stating that the argument '"login"' cannot be assigned to the parameter of type 'keyof Chainable<any>))`

Attempting to simplify repetitive actions by utilizing commands.ts, such as requesting email and password. However, upon trying to implement this, I encounter an error for the login (Argument of type '"login"' is not assignable to parameter of t ...

Steps to prevent subfolder imports in my npm package

My npm package is built using: typescript webpack webpack.config: {... entry: './src/index.ts } library tree: - package.json - src - - index.ts - - ...all_my_code... I have all my library functionality and types exported from the index.ts file. T ...

Troubleshooting Authorization Header Issue in Angular 5

I created an Interceptor to include an Authorization token in all HTTP Requests, but unfortunately it's not functioning as expected. I've double-checked my code and everything seems correct, so I'm wondering if there's something crucial ...

Suggested imports in a yarn monorepo are not being automatically added when selected

I've noticed that many people are asking similar questions, but my situation seems a bit unique as I haven't found anyone else with the same issue. Currently, I'm working on a file in packages/frontend/client, specifically packages/frontend ...

What steps should I take to resolve the issue of 'unable to locate the name 'OktaAuthService' error?

I am currently trying to incorporate authentication into an Angular application using Okta. I have carefully followed the step-by-step instructions provided in the documentation at this link: . However, I am encountering an error when attempting to start t ...

Observable subscription not updating HTML with changes

My challenge is passing an object to the Object Model using a shared service to an already loaded component. Even though I receive data after subscribing, it does not reflect in the HTML view. <div *ngFor="let emp of emps" class="card&q ...

Using Angular 2 for form validation

Hey there, I'm currently using Angular 2 and I need to set the password field requirements to include at least 1 uppercase letter, 1 lowercase letter, 1 number, 1 special character with a minimum of 8 characters and maximum of 16 characters. So far, ...

How to Implement checked radio buttons in Angular 2 using ngModel

When generating radio buttons in Angular, I am using the following code: <div class="radio" *ngFor="let gender of genders"> <input type="radio" name="gender" [checked]="gender=='male'" [value]="gender"> {{gender}} </div> ...

Customizing the Position of Material UI Select in a Theme Override

I'm trying to customize the position of the dropdown menu for select fields in my theme without having to implement it individually on each select element. Here's what I've attempted: createMuiTheme({ overrides: { MuiSelect: { ...

Is there a way to verify if the object's ID within an array matches?

I am looking to compare the ID of an object with all IDs of the objects in an array. There is a button that allows me to add a dish to the orders array. If the dish does not already exist in the array, it gets added. However, if the dish already exists, I ...

Encountering a DOMException while attempting to update the value of a textarea

Here is the HTML code snippet: <textarea formControlName="post-content" (keyup)="check(myText)" [(ngModel)]="myText"> </textarea> My check function looks like this: checkText(text) { // Cannot change the value of (myText) ...

When the request's credentials mode is set to 'include', the 'Access-Control-Allow-Origin' header value in the response should not be the wildcard character '*'

I'm currently in the process of establishing a connection between my Angular application and Node.js using a GraphQL API, utilizing cookies/sessions for authentication purposes. The GraphQL Playground successfully interacts with the API. Here is how ...

Tab-based Ionic 2 advertising campaign featuring banners

Is there a way to incorporate an advertisement banner image above the tabs in ionic 2? Any suggestions on how I can achieve this or create the banner in that specific position? ...

lines stay unbroken in angular

I am encountering an issue when I execute the following code: DetailDisplayer(row) : String { let resultAsString = ""; console.log(row.metadata.questions.length); (row.metadata.questions.length != 0 )?resultAsString += "Questions ...

What is the solution to resolving a Typescript error within an imported library?

I've encountered a Typescript error that I'm unable to resolve because it doesn't originate from my code. The issue arises when I import a NextJs/React module named next-seo and use it as instructed: <NextSeo config={seoConfig} /> The ...

A property in TypeScript with a type that depends on the value of an object

How can we troubleshoot the error not displaying in Typescript and resolve it effectively? Explore Typescript sandbox. enum Animal { BIRD = 'bird', DOG = 'dog', } interface Smth<T extends Animal = Animal> { id: number; a ...

Issue with the integration of Angular and Java Jersey API arises when attempting to encode utf-8 whitespaces at the end, resulting in invalid JSON

I'm facing an issue with Angular while making an HTTP GET request. It throws a "Http failure during parsing" error because the JSON response contains whitespace characters at the end. I find it puzzling why the server is returning them. Is there a wa ...

Tips for converting necessary constructor choices into discretionary ones after they have been designated by the MyClass.defaults(options) method

If I create a class called Base with a constructor that needs one object argument containing at least a version key, the Base class should also include a static method called .defaults() which can set defaults for any options on the new constructor it retu ...

Error: The function call does not match any of the overloads. 'VueRouter' is not recognized

I'm new to TypeScript and currently trying to implement vue-router in my project. Encountering the following errors: Error TS2769: No overload matches this call in source\app\main.ts(3,3). Overload 1 of 3, '(options?: ThisTypedCompon ...