简体   繁体   English

如何根据Angular中的API数据生成动态tab

[英]How to generate dynamic tab based on API data in Angular

I have below json response.我有以下 json 响应。

From json response i am creating dynamic tab and inside every tab i want to push formArray based on below mentioned condition.从 json 响应中,我正在创建动态选项卡,并且在每个选项卡内我想根据下面提到的条件推送 formArray。

**In below response, **在以下回复中,

 const myObj = [
          {
            'TabName': 'Test1',
            'otherDetails': [
              {
                'processTechType': 'Continuous'
              },
              {
                'processTechType': 'Batch',
              },
            ]
          },
          {
            'TabName': 'Test2',
            'otherDetails': [
              {
                'processTechType': 'Batch'
              }
            ]
          }
        ];

For Ex -** TabName Test1 and TabName Test2 are tabs name which i am displaying dynamically.对于 Ex -** TabName Test1 和 TabName Test2 是我动态显示的选项卡名称。 Now in Test1 Tab , i want to push formArray Continuous and formArray Batch both forms.现在在 Test1 选项卡中,我想同时推送formArray Continuous 和 formArray Batch forms。 Because in Test1 Tab, i have processTechType array with Continuous and batch both.因为在 Test1 选项卡中,我有带有 Continuous 和 batch 的 processTechType 数组。 So it will show both form in Test1 Tab.因此它将在 Test1 选项卡中显示两种形式。

Ex - 2 -- Now in Test2 Tab, i want to push formArray Batch form only. Ex - 2 --现在在 Test2 选项卡中,我只想推送 formArray Batch 表单。 Becuase in Test2 Tab, i have processTechType batch in otherDetails object.因为在 Test2 选项卡中,我在 otherDetails object 中有 processTechType 批次。 So it will show Batch form only in Test2 Tab.所以它只会在 Test2 选项卡中显示批处理表单。

My mean to say is everytime it will check the Tabname and otherDetails key from response and show forms based on processTechType array key on specific tab only.我的意思是每次它会检查响应中的 Tabname 和 otherDetails 键,并仅在特定选项卡上基于 processTechType 数组键显示 forms。

I have below code.我有以下代码。 But it is pushing both forms in all tabs, not on specific tab.但它在所有选项卡中都推送 forms,而不是在特定选项卡上。 For ex - From my code, It is showing Continuous formArray onetime and Batch formArray two times in Test1 and Test2 tabs both.例如-从我的代码中,它在 Test1 和 Test2 选项卡中都显示了 Continuous formArray onetime 和 Batch formArray 两次。

Expected output -预期 output -

In Test1 Tab, it will push one Continuous and one Batch form.在 Test1 选项卡中,它将推送一个连续表单和一个批处理表单。

In Test2 Tab, It will show push batch form only.在 Test2 选项卡中,它将仅显示推送批处理表单。

Can anyone please help me get my code work to get my expected output.谁能帮我完成我的代码工作以获得我预期的 output。

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.processTechType === 'Continuous') {
            this.addQuantity();
          }
          else if (i.processTechType === 'Batch')  {
            this.addBatch();
          } 
        }
      });      
    } 
}

createContinuousForm() {
    return this.fb.group({
      designProcess: ['', [Validators.required]]
    });
  }
  createBatchForm() {
    return this.fb.group({
      avgBCT: ['', [Validators.required]]
    });
  } 
  continuousType(): FormArray {
    return this.dataCollectionForm.get("continuousType") as FormArray;
  }

  batchType(): FormArray {
    return this.dataCollectionForm.get("batchType") as FormArray;
  }

  addQuantity() {
    this.continuousType().push(this.createContinuousForm());

  }
  addBatch() {
    this.batchType().push(this.createBatchForm());
  }

HTML form template HTML 表单模板

<div class="tabGroupDiv row">
    <div class="lossLinesDiv">     
      <mat-tab-group class="lossMatGrpCls" mat-align-tabs="left">
        <mat-tab *ngFor="let lineData of makeLineData">
          <ng-template mat-tab-label>
                <button class="validatorTabBgClr">{{lineData.makeLineName}}</button>
          </ng-template>
          <form [formGroup]="dataCollectionForm" (ngSubmit)="onSubmit()">
            <!-- <--continuous Form start here -->  
            <div class="admin-console-main-wrapper" formArrayName="continuousType">
              <div class="content-wrapper" *ngFor="let lineItem of continuousType().controls; let i=index"
                [formGroupName]="i">
              
                <div class="row list-wrapper">
                  <div class="col-xs-3 col-md-3 deo-dv-list-wrapper">
                    <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>
                    <mat-error *ngIf="lineItem?.controls?.designProcess?.hasError('required')">
                      Field is required
                    </mat-error>
                  </div>
                </div>              
              </div>
            </div>  
            <!-- <--continuous Form start here -->
  
            <!-- <--Batch Form start here -->
            <div class="admin-console-main-wrapper" formArrayName="batchType">
              <div class="content-wrapper" *ngFor="let lineBatchItem of batchType().controls; let i=index"
                [formGroupName]="i">               
  
                <div class="row list-wrapper">
                  <div class="col-xs-3 col-md-3 deo-dv-list-wrapper">
                    <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>
              </div>
            </div>  
            <!-- <--Batch Form ends here -->
          </form>
        </mat-tab>
      </mat-tab-group>
    </div>
  </div>

The structure has been written for one dataCollectionForm not multiple.该结构是为一个dataCollectionForm而不是多个编写的。 What is mean is there is seperation of dataCollectionForm by tabs.意思是 dataCollectionForm 由选项卡分隔。 Unless on change of tab you recreate the form, this should not work.除非在更改选项卡时重新创建表单,否则这应该不起作用。

  1. dataCollectionForm should be a collection of form group, by some id. dataCollectionForm应该是表单组的集合,由一些 id 组成。
  2. Don't over complicate with in correct user of filter and map不要过度复杂化过滤器和 map 的正确用户

Sudo Code below, might need correction, just there to give you direction:下面的 Sudo 代码,可能需要更正,只是为了给你方向:

 public makeLineData: any[] = []; // object with otherDetails

   // will contain form based on myObj index
   public dataCollectionForm: FormGroup[] = []; // in template loop over this by index

 createForm() { // getMakeLineData name correction

    myObj
   .filter(m => m.otherDetails)
   .forEach((obj) => {
     // create and push From in dataCollectionForm
     this.makeLineData.push(obj);
     let dataFrom =  this.addTabDataCollectionForm();

     obj.otherDetails.forEach((detail) => {
       if (detail.processTechType === 'Continuous') {
            this.addQuantity(dataFrom);
          }
          else if (detail.processTechType === 'Batch')  {
            this.addBatch(dataFrom);
          } 
     })

   
   })

    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.processTechType === 'Continuous') {
            this.addQuantity();
          }
          else if (i.processTechType === 'Batch')  {
            this.addBatch();
          } 
        }
      });      
    } 
}

addTabDataCollectionForm (): FromGroup {
  // this will represet the form of one single tab;
  let tabDataForm = this.fb.group({
      continuousType: new FormArray([])
      batchType: new FormArray([])
    });

    this.dataCollectionForm.push(tabDataForm); 
    return tabDataForm; 
    
}

createContinuousForm() {
    return this.fb.group({
      designProcess: ['', [Validators.required]]
    });
  }
  createBatchForm() {
    return this.fb.group({
      avgBCT: ['', [Validators.required]]
    });
  } 

  continuousType(dataFrom): FormArray {
    return dataFrom.get("continuousType") as FormArray;
  }

  batchType(dataFrom): FormArray {
    return dataFrom.get("batchType") as FormArray;
  }

  addQuantity(dataFrom) {
    this.continuousType(dataFrom).push(this.createContinuousForm());

  }
  addBatch(dataFrom) {
    this.batchType(dataFrom).push(this.createBatchForm());
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Angular8中使用基于API的数据生成动态选项卡 - How to generate dynamic tab with data based on API in Angular8 如何通过数组映射生成基于api响应的动态表单? - How to map through the array to generate dynamic form based on api response? 根据变量angular生成动态css - Generate dynamic css based on variables angular 如何根据从 JSON 接收到的数据生成动态表单 - How to generate dynamic form based on data received from JSON 如何为adal-angular6配置生成动态数据 - how to generate dynamic data for adal-angular6 configuration 为角度的动态数据生成嵌套结构 - Generate nested structure for dynamic data for angular 基于其他数据的角度动态验证 - Angular dynamic validation based on other data NodeJS:创建 api,它将设法根据键值动态生成 for 循环 - NodeJS: Create api that will manage to generate the for loop as dynamic based on key value 我可以将基于RESTful api的服务器端的初始动态数据传递到基于角度的前端页面吗? - Can I pass along initial dynamic data from a RESTful api based server side, to an angular based front end page? 如何使用 PHP 和 MySQL 从 Google Chart API 生成动态数据? - How to generate dynamic data from Google Chart API using PHP and MySQL?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM