Exploring Angular data iteration with Tab and its contentLearn how to loop through Tab elements

Upon receiving a response from the API, this is what I get:

const myObj = [
  {
    'tabName': 'Tab1',
    'otherDetails': [
      {
        'formType': 'Continuous'
      },
      {
        'formType': 'Batch',
      }
    ]
  },
  {
    'tabName': 'Tab2',
    'otherDetails': [         
      {
        'formType': 'Batch',
      }
    ]
  }    
];

In the function below, I am processing tabs and pushing form arrays based on API data. The issue at hand is that both continuous and batch forms are appearing multiple times in every tab.

getMakeLineData() {  
var otherDetails = myObj.filter(m => m.otherDetails).map(m => m.otherDetails);
this.makeLineData = myObj;
if (otherDetails) {
  otherDetails.forEach(element => {       
    for (var i of element) {
      if (i.formType === 'Continuous') {           
         this.continuousType().push(this.createContinuousForm());
      } else if (i.formType === 'Batch')  {            
         this.batchType().push(this.createBatchForm());
      } 
    }
  });      
}
}

I need help creating the correct logic to achieve the desired outcome.

Based on the above response, I need to iterate through dynamic tabs and push batch and continuous forms related to each tab.

Expected output -

In Tab1 - Both Continuous and Batch form arrays should be pushed because in the response of Tab1 there are both batch and continuous form types in the otherDetails key.

In Tab2 -Only the batch form array should be pushed because in the response of Tab2 there is only the batch form type in the otherDetails key.

Here is my HTML:

<mat-tab-group class="lossMatGrpCls" mat-align-tabs="left">
    <ng-container *ngFor="let lineData of makeLineData">
        <mat-tab>
            <button class="validatorTabBgClr">{{lineData.tabName}}</button>

            <div *ngFor="let line of lineData.otherDetails">
                <form [formGroup]="dataCollectionForm" (ngSubmit)="onSubmit()">
                    <!-- <--continuous Form start here -->
                    <div *ngIf="line && line.formType === 'Continuous'">
                        <div class="admin-console-main-wrapper" formArrayName="continuousType">
                            <div class="content-wrapper" *ngFor="let lineItem of continuousType().controls; let i=index"
                                [formGroupName]="i">
                                <h5 class="topbar-items-text">Design Process Capacity (Tonnes)</h5>
                                <mat-form-field appearance="outline">
                                    <input matInput type="text" class="line-fte-input smed-input"
                                        placeholder="Design Process Capacity" formControlName="designProcess">
                                </mat-form-field>
                            </div>
                        </div>
                    </div>
                    <!-- <--continuous Form start here -->

                    <!-- <--Batch Form start here -->
                    <div *ngIf="line && line.formType === 'Batch'" class="admin-console-main-wrapper"
                        formArrayName="batchType">
                        <div class="content-wrapper" *ngFor="let lineBatchItem of batchType().controls; let i=index"
                            [formGroupName]="i">
                            <h5 class="topbar-items-text">Average BCT (mins)</h5>
                            <mat-form-field appearance="outline">
                                <input matInput type="text" class="line-fte-input smed-input" placeholder="Average BCT"
                                    formControlName="avgBCT">
                            </mat-form-field>
                        </div>
                    </div>
                    <!-- <--Batch Form ends here -->
                </form>
            </div>
        </mat-tab>
    </ng-container>
</mat-tab-group>

Answer №1

Opting for template-driven forms over reactive forms is a simpler solution. All you have to do is define the form-field property in your array of objects.

<mat-tab-group>
  <mat-tab *ngFor="let tab of asyncTabs">
    <ng-template mat-tab-label>{{ tab.tabName }}</ng-template>
    <ng-container *ngFor="let line of tab.otherDetails">
      <form>
        <div *ngIf="line && line.formType === 'Continuous'">
          <h5 class="topbar-items-text">Design Process Capacity (Tonnes)</h5>
          <mat-form-field appearance="outline">
            <input
              matInput
              type="text"
              [(ngModel)]="line.value"
              name="value"
              placeholder="Design Process Capacity"
            />
          </mat-form-field>
        </div>
        <div *ngIf="line && line.formType === 'Batch'">
          <h5 class="topbar-items-text">Average BCT (mins)</h5>
          <mat-form-field appearance="outline">
            <input
              matInput
              type="text"
              [(ngModel)]="line.value"
              name="value"
              placeholder="Average BCT"
            />
          </mat-form-field>
        </div>
      </form>
    </ng-container>
  </mat-tab>
</mat-tab-group>

Live Example:- https://stackblitz.com/edit/angular-ivy-t1infl?file=src%2Fapp%2Fapp.component.html

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

Make sure to use the jQuery load function to specifically target and retrieve

Hello, I'm new to working with jQuery and I have a question about adding a vertical scrollbar to a jQuery modal window. Specifically, I want the scrollbar to appear when there is a large amount of text within the modal window. Can you guide me on wher ...

Injecting Basic Data Types into Your Angular 2 Service

I am facing an issue with a basic service that requires a single string parameter. import {Injectable} from 'angular2/core'; @Injectable() export class MyService { constructor(someValue: string) { } } When I remove the string param fro ...

Error: The first certificate could not be verified, although I included rejectUnauthorized: false option

I have encountered an issue with my getServerSideProps() function, as it is throwing an error when trying to call an external API: FetchError: request to https://nginx/api/items failed, reason: unable to verify the first certificate The self-signed cert ...

How to Implement Route Resolution for Nested Components in Angular 4?

In my current setup, I have the following hierarchy: Parent Component |__Nested Component 1 |__Nested Component 2 |__Nested Component 3 The challenge I am facing is resolving data into Nested Component 3 since only the Parent Component has a rout ...

Leveraging Component without the need for Import

Is it possible to use a component without re-importing it if it's already declared in AppModule? With 10 or more pages/components to manage, importing each one can be challenging. Here is my app.module.ts import { NgModule, ErrorHandler } from &apos ...

What is the best way to retrieve a value from a function that contains multiple nested functions in Javascript?

The issue at hand is my struggle to extract a value from a nested method and utilize it outside of its parent method. I am aiming for the output of "console.log(someObjects[i].valueChecker);" to display either "true" or "false," but instead, it simply retu ...

Display the properties of the nested object

I am trying to extract and print the postal_code value from the JSON file provided below: { "results" : [ { "address_components" : [ { "long_name" : "286", "short_name" : "286", "t ...

Display more/hide less form using div elements in a NextJS project

Looking to create a hidden block of amenities on my hotel website that can be expanded and collapsed with buttons in NextJS using tailwind-css. How can I achieve this functionality? Example 1: https://i.stack.imgur.com/BbrUj.png Example-2: https://i.stac ...

Create a new array by applying a filtering function to the provided data in JavaScript using React

I am a beginner in the world of React. I have an object containing an array (Map) as follows: "POSSIBLE_UPDATE_OPTIONS": { "Process": ["confirm"], "Confirmed": [ "Process", ...

Using Framework7 and AngularJS to efficiently load pages

When creating a phone application using phonegap, AngularJS, and Framework7, I encountered an issue with the page swapping functionality of Framework7. The problem arises because Framework7 injects new HTML pages into the DOM dynamically when a user click ...

Using JQuery to create multiple dropdown lists with the functionality of disabling the selected entry in other lists

I have a challenge with multiple dropdown lists. When I select an option in one, I want it to be disabled in the others so that it cannot be selected again. However, if the option is deselected, then I need it to become available in the other lists. Curr ...

Tips for switching "a" tag elements to reveal concealed DIVs in a similar way to the Facebook notification center

I have a situation in my code where I need to toggle between two a elements to display a hidden div with content one at a time. This functionality is similar to how the Facebook notification center works when you click on the icons, which I'm sure mos ...

Implementing Vue.js functionality to dynamically add or remove values from an array based on the state of a checkbox

I recently embarked on my journey to learn vue.js and I've encountered a challenging issue. I have dynamic data that I render using a 'v-for' loop. Additionally, I have an empty array where I need to store checked checkbox data and remove it ...

Retrieve information from every nested array and present it in sequential order

I need to extract the index of each element in a nested array structure. For example, I have an array with 5 subarrays, each containing multiple elements. My goal is to retrieve the first element from each subarray, then the second element, and so on. Her ...

Navigating the loading of information with fetch and React Hooks

As a newcomer to React and still learning JavaScript, I am facing a challenge with handling useEffect alongside an asynchronous function. My goal is to fetch data from an API and render a quote in the paragraph with id of text, along with the author's ...

The function chartobject-1.render() is returning an error message stating: "Unable to locate the specified container within the document. This issue is occurring in the

I've encountered an issue while trying to integrate FusionCharts into my Vue.js project. Every time I attempt to render the charts within my components, I consistently run into this error. Here's a snippet of one of the components: <template&g ...

Do AJAX calls necessitate the use of 200 OK messages to successfully execute a server side request?

We are working on a tracking system that involves making three consecutive ajax calls within the WordPress environment using the WordPress AJAX API. On the third call, it triggers a page refresh. I have observed that sometimes one of my data entry attempt ...

Struggling to make jeditbale ajax call function properly

Currently, I am attempting to modify text directly on the webpage using the jeditable plugin. Unfortunately, I have encountered a challenge when it comes to saving the updated data properly through an ajax call. Although I can successfully edit the text, i ...

Is there a way to customize the selected option in the autocomplete feature of Material UI components?

Is it possible to customize the CSS of selected options in Material UI autocomplete? Can this be achieved by utilizing the theme? ...

Error message: Error in jQuery: Object is required for Internet

I have a button that is designed to trigger the opening of a jQuery UI Dialog when clicked. Strangely, it works perfectly in FF3, FF4, Chrome, and IE8 with ChromeFrame, but fails to function in regular IE8. The error message displayed simply states "Object ...