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

Controlling the activation of a button on a parent modal popup from a child within an IFrame using javascript

I am struggling to toggle the button on the main window from the child window. Here is a snippet from the main page: <ajaxToolkit:ModalPopupExtender ID="mpeTest" runat="server" CancelControlID="btnClose" PopupControlID="pnl1" TargetControlID="showMp ...

Issues with APIs surfaced following the transition from DataGridPro to DataGridPremium

In my current project, we initially implemented the MUI X DataGrid but later switched to DataGridPro due to business requirements. Recently, we upgraded our plan from Pro to Premium which has caused some unexpected issues in our existing code. I am using " ...

What steps can be taken to troubleshoot and resolve this specific TypeScript compilation error, as well as similar errors that may

I am struggling with this TypeScript code that contains comments and seems a bit messy: function getPlacesToStopExchange(): { our: { i: number; val: number; }[]; enemy: { i: number; val: number; }[]; //[party in 'our' | 'enemy' ]: ...

What is the correct way to integrate the Ant Design library with Next.js for seamless server-side rendering?

I duplicated the official Next.js example using Ant Design at this link: https://github.com/vercel/next.js/tree/canary/examples/with-ant-design After cloning, I proceeded with npm install to install all dependencies. Then, I ran npm run dev to check if ev ...

Show the total of a JavaScript calculation in a designated input box

Is there a way to show the total sum of this calculation in an input field? function calculateSum1() { var sum = 0; //loop through each textbox and add their values $("input.miles").each(function() { //only add if the value is a number ...

Drag and Drop Feature using Angular with JQuery UI for Cloning Elements

I've been working on a web design project where I want to create a draggable user interface. https://i.sstatic.net/Be0Jk.png The goal is for users to click and drag different types of questions from the left side to the right side of the screen. Cu ...

Enhancing Function Calls for Better Performance in V8

Is V8 capable of optimizing repeated function calls with identical arguments? For instance, in the code snippet below, Variance is invoked twice with the same arguments. var Variance = require('variance'); function summary(items) { ...

Ways to disable .animate() specifically for a particular element

I have implemented a countdown using which smoothly animates the numbers down and fades to opacity 0. Update. I have also created a demo on jsFiddle here: http://jsfiddle.net/Mw4j2/ // The .static class is added when the animation // complet ...

What are some ways to enhance the opacity of a Material UI backdrop?

I'm looking to enhance the darkness of the material UI backdrop as its default appearance is not very dark. My goal is to make it dimmer and closer to black in color. ...

Navigating with Angular 7

Encountering an issue with my Angular 7 Application Here is the error message: Error: Invalid configuration of route 'dashboard'. One of the following must be provided: component, redirectTo, children or loadChildren In the process of develo ...

The 'component' property is not found in the 'IntrinsicAttributes' type in this context

I am facing an issue with a component that is not compiling properly: export default function MobileNav({routes, currentRouteIndex, handlePressedRoutedIndex}: MobileNavProp) { ... return ( <React.Fragment> ... ...

Different Options to Explore Instead of Using @apollo/federation Library

We are currently developing typescript microservices with REST APIs and are exploring the possibility of integrating GraphQL into each microservice, along with implementing an API Gateway at the top level to combine everything into a single API. Although ...

Guide to retrieving table data using jQuery in a Vue.js function

I have a simple table set up in my Laravel blade file. When the edit button is clicked, it triggers a Vue method. <types-page inline-template> <div> <!-- table --> <table id="choose-address-tab ...

How can you send Django context data to a JavaScript variable?

I need to send each value of the {{ i.nsn }} to the ajax script one by one. {% for i in dibbs %} <p>{{ i.nsn }}</p> {% endfor %} Instead of repeating the ajax script, I want it to function with a single click. <script> var nsn = " ...

In Django, the Ajax function will fail to execute if any of the required input fields are left empty

I'm currently using an AJAX function that works well when values are entered for all three fields: pname, psection, and rinput-json. However, it fails to work if any of these fields are left empty. <script type="text/javascript"> funct ...

What could be causing the malfunction of Bootstrap Multiselect functionality?

I have been attempting to set up Bootstrap Multiselect but it simply refuses to work. Despite trying various solutions, I am unable to pinpoint the issue. My index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF- ...

What is the best way to animate an element when it comes into the user's view

In order to activate the animation of the skill-bars when the element is displayed on the website, I am seeking a solution where scrolling down through the section triggers the animation. Although I have managed to conceptualize and implement the idea with ...

How to troubleshoot WordPress Ajax function not getting form data

I am currently working on a form in my plugin where I need to send data to my AJAX action function using the standard WP Ajax techniques. Here is the basic structure of my form: <form role="form" id="signup_widget_form" method="post" action="#"> ...

Guideline on extracting private keys from Windows Certificate Manager

I am currently working in a Windows environment setting. Within my organization, we act as our own certificate authority for internally-used https applications. I have obtained a certificate from our system for a private web server I created. While using ...

Why isn't httpUploadProgress functioning correctly with Buffer data?

Recently, I have ventured into the world of node.js/express as I am attempting to create a multiple image uploading application utilizing cloudfront and an s3 bucket. My goal is to display a progress bar for the user by integrating socket.io for real-time ...