Enter data into the appropriate columns

Within my Angular 6 application, I am creating a table with the following structure:

Html:

<table>
    <thead>
        <tr>
            <th>
                Property Details &nbsp; &nbsp; &nbsp; &nbsp;
            </th>
            <th>
                {{productOneDetails}}  &nbsp; &nbsp; &nbsp; &nbsp;
            </th>
            <th>
                {{productTwoDetails}} 
            </th>
        </tr> <br>
    </thead>
    <tbody>
        <tr *ngFor="let item of mergedArray">
      <td> {{ item.property_name }} </td>
      <td> {{ item.property_value }} </td>
      <td> {{ item.property_value }} </td>
        </tr>
    </tbody>
</table>

In this setup, there are two arrays within the products object - product one and product two.

The goal is to merge both sets of properties, this.productOneProperties and this.productTwoProperties, and display the combined result in the table.

All functionality currently works as intended.

Working example: https://stackblitz.com/edit/angular-iv8ckz

You will find the current output as follows:

Property Details            Product One         Product Two

Length                        12cm                12cm
Width                         10cm                10cm
Height                        20cm                20cm
Color                         Red                 Red
Size                          Medium              Medium

The desired expected output should be:

Property Details            Product One         Product Two

Length                        12cm                -
Width                         10cm                -
Height                        20cm                -
Color                         -                   Red
Size                          -                   Medium

To achieve this, it is necessary to merge both arrays and feature all properties under the Property Details column.

If a property is only present in one product, the corresponding value should be displayed. Otherwise, show a "-" symbol for empty values.

I trust you understand my requirements and kindly request assistance converting the current output to match the expected output.

Answer №1

To properly identify each product, assign a type to every object and then use conditions from the template for evaluation.

this.products.productOne.forEach(element => {
  this.productOneDetails = element.product_name; 
  this.productOneProperties = element.productOneProperties.map(item => {item.type = "one"; return item});
});
this.products.productTwo.forEach(element => {
  this.productTwoDetails = element.product_name; 
  this.productTwoProperties = element.productTwoProperties.map(item => {item.type = "two"; return item});

HTML

<tr *ngFor="let item of mergedArray">
  <td> {{ item.property_name }} </td>
  <td> {{ item.type === "one" ? item.property_value: '-' }} </td>
  <td> {{ item.type === "two" ? item.property_value: '-'  }} </td>
 </tr>

Check out the demo here

Answer №2

The issue lies in the table structure, where the same property is being used to display variables in both columns, resulting in them always showing the same value.

A simple solution would be to associate each object with the product it belongs to. This way, filtering becomes easier:

In the ngOnInit function:

ngOnInit() {
    this.products.productOne.forEach(element => {
      this.productOneDetails = element.product_name;
      this.productOneProperties = element.productOneProperties;
      this.productOneProperties.map(p => {
        p.product = 1;
      });
    });

    this.products.productTwo.forEach(element => {
      this.productTwoDetails = element.product_name;
      this.productTwoProperties = element.productTwoProperties;
      this.productTwoProperties.map(p => {
        p.product = 2;
      });
    });

    this.mergedArray = [...this.productOneProperties, ...this.productTwoProperties];
}

Update your HTML's <tr>:

<tr *ngFor="let item of mergedArray">
  <td> {{ item.property_name }} </td>
  <td> {{ item.product === 1 ? item.property_value : "-" }} </td>
  <td> {{ item.product === 2 ? item.property_value : "-" }} </td>
</tr>

If you prefer not to modify the TypeScript file, you can achieve the desired result by updating the <tr> as follows:

<tr *ngFor="let item of mergedArray">
  <td> {{ item.property_name }} </td>
  <td> {{ productOneProperties.indexOf(item) !== -1 ? item.property_value : "-" }} </td>
  <td> {{ productTwoProperties.indexOf(item) !== -1 ? item.property_value : "-" }} </td>
</tr>

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

"Encountering issues while upgrading Polymer project version from 0.5 to 1.0

I am in the process of upgrading my project from polymer .5 to polymer 1.0. After installing the new version of the polymer library, iron element, and paper element, I encountered the following error: polymer-micro.html:63 Uncaught TypeError: prototype ...

Utilizing React Typescript to dynamically render a duo of components

On a single page, I want to display two components simultaneously. There is a bottom navbar that, when clicked on, for example the profile icon, should render the profile page. However, I would like to change the color of the icon based on which component ...

Issue with Jquery Drag and Drop functionality, navigate to a different page

I am trying to incorporate a page with js from quotemedia.com using Jquery. When I insert the js into the sortable, and then drag and drop the element containing the js, it suddenly switches to full page display. This issue occurs in Firefox, but IE works ...

Retrieving information from a datatable in vb.net with an array

Working on a chart using highcharts with code behind in vb.net... I have a datatable structured like this: Date - speed - data 2011 10k 6 2011 18k 7 2012 20k 10 2012 10k 2 2013 14k 4 2013 20k 6 Previously, to ...

Some code paths fail to return a value in Google Cloud Function callable functions

When utilizing async functions in my cloud function and including a 'return' statement in each potential output, I am still encountering the error message Not all code paths return a value I attempted removing my database calls and only leaving ...

What is preventing me from translating JS Canvas Image?

I've been struggling with using ctx.translate() to translate images on a canvas. No matter what I do, it just won't work. I've spent a good amount of time trying to troubleshoot the issue. Here's the snippet of code I'm working wit ...

Transforming an unordered list to function similarly to a select input

I am looking to style a ul list to function as a select form element. I have successfully populated a hidden input using my code. Now, I am trying to make the ul behave like a select input when either the keyboard or mouse is used. Previously, I had some ...

Can the individual headers of an ag-grid column be accessed in order to apply an on-mouseover event with a specific method?

In my current project, I am utilizing ag-grid to create a dynamic web-application that combines tools from various Excel files into one cohesive platform. One of the Excel features I am currently working on involves displaying a description when hovering ...

I've been stuck for hours, is there anything I should include?

I'm attempting to access http://localhost:4200/Personnes/view/:2, but I encountered the following error (ERROR TypeError: Cannot read property 'nom' of undefined) "My personnnes.service.component.ts" `export class PersonnesService { baseUr ...

Tips for transferring parameters between functions in AngularJS

I'm currently working with the following piece of code: var FACEBOOK = 'facebook'; $scope.handle_credentials = function (network) { hello(network).api('me').then(function (json) { dbService.handle_credential ...

Dynamic image sources in reusable Gatsby-Image Component

Recently, I have been exploring Gatsby-Image for an upcoming project and have started experimenting with its capabilities. My test project was successful, but now I want to utilize the <Image /> tag from Gatsby in a similar way to a standard <img ...

Make the textarea larger and bring it to the forefront when it is selected

I would like to make a textarea expand (increase its height) when it is in focus. The expanded textarea should not push the content down, but rather be displayed above other content. Currently, this is the code I am using (check out the example here): $( ...

Trying out the MatDialogRef overlayref: A step-by-step guide

What is the best way to test dialogref coming from MatDialogRef? dialogRef: MatDialogRef<testComponent>; displayBackdrop() { const backdrop = this.dialogRef['_ref'].overlayRef._backdropElement.style.display = 'block' ...

Ensuring that each object in a list contains an optional key if any one object includes it is a task handled by Joi validation

My dataset includes various objects that must have certain keys: Date, Time, Price I am looking to include an optional key "order" for these objects. If one of them has the "order" key, then they all should. Is there a way to validate this using joi? ...

Executing a function when clearing an autocomplete textfield in Material-UI

Currently, I am working with a material-ui autocomplete text field in order to filter a list. My goal is to have the list repopulate back to its original form when the user deletes the text and presses the enter key. After my research, it seems like the ...

Successive type label

Looking to create an object that can have either primitives or objects as properties? Avoid pitfalls like the following: const obj: DesiredType = { correctProp1: 'string', correctProp2: 123, correctProp3: true, wrongProp4: [1, 2, 3], pr ...

Tips for ensuring the angular FormArray is properly validated within mat-step by utilizing [stepControl] for every mat-step

When using Angular Material stepper, we can easily bind form controls with form groups like [stepControl]="myFormGroup". But how do we bind a FormArray inside a formGroup? Constructor constructor(private _fb: FormBuilder){} FormArray inside For ...

Attempting to single out various entities within a JSON array through the use of radio buttons

I am currently developing a website to showcase sports teams' schedules. Each team has its own JSON file containing relevant information that I aim to display upon selecting the team from a radio button. For instance, let's consider the example ...

Nodejs restricts the user from performing the action

Currently, I am utilizing Nodejs with Expressjs and encountering an issue when trying to run the project. The connection is established successfully but when attempting to access the URL (localhost:3001/api/plans), an error appears in the console: MongoSer ...

The chosen Angular material pre-built theme of indigo-pink does not seem to be applied properly

Within my styles.scss @import '~@angular/material/prebuilt-themes/indigo-pink.css'; I have also attempted this in my index.html <link href="node_modules/@angular/material/prebuilt-themes/indigo-pink.css" rel="stylesheet" /> Finally, I m ...