Angular 从多个选择中获取表单数据

Angular get Formdata from multiple Selections

我在将传入的“随机”字段与我的架构链接后尝试获取我的表单数据,以便我可以在我的代码中使用它。

我收到了一些带有不同“headers”的数据,我想通过公式和选择将这些随机 headers 设置到我的架构中。我的问题是我无法获得“映射”数据。我的表格是空的。我尝试了反应形式方法,但我没有在最后一步工作,我必须绑定我的字段。

带有 formcontrol 的简单字段工作正常。

您可以在 link.

下找到我的代码

也许有人可以帮助我。

我们需要为 incomingFieldNames 中的每个字段创建单独的 formControl,并且需要将其推入表单数组。

请查看下方

selection.component.ts

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup } from '@angular/forms';
import { FormArray, Validators } from '@angular/forms';

@Component({
  selector: 'app-selection',
  templateUrl: './selection.component.html',
  styleUrls: ['./selection.component.scss']
})
export class SelectionComponent implements OnInit {
  formData: FormGroup;

  // language selection
  lanugages: any[] = [
    { name: 'Italian', id: 1 },
    { name: 'Polish', id: 2 },
    { name: 'Czech', id: 3 },
    { name: 'English', id: 4 },
    { name: 'German', id: 5 }
  ];

  // default lang
  language: number = 2;

  // data for tablenames / header
  incomingFieldNames: string[] = [
    'ArticleNR',
    'Articleinformation',
    'Articleprize',
    'Articlesomething'
  ];

  newHeaderFieldsToMap: any[] = [
    { name: 'Articlenumber', value: 'artNr' },
    { name: 'Description / Name', value: 'artDesc' },
    { name: 'Prize', value: 'artPrize' }
  ];

  constructor(private fb: FormBuilder) {}

  ngOnInit(): void {
    this.formData = this.fb.group({
      language: [this.language, Validators.required],
      fields: this.fb.array([])
    });
    this.addFormArray();
  }

  get headerData() {
    return this.formData.controls['fields'] as FormArray;
  }

  addFormArray() {
    this.incomingFieldNames.map(field => {
      this.headerData.push(new FormGroup({ [field]: new FormControl()}))
    })
  }

  onSubmit() {
    console.log(this.formData.value);
  }
}

selection.component.html

<h4>Data</h4>
<mat-divider></mat-divider>
<form [formGroup]="formData" (ngSubmit)="onSubmit()">
  <mat-form-field appearance="fill">
    <mat-label>Select language</mat-label>
    <mat-select name="language" formControlName="language">
      <mat-option *ngFor="let lang of lanugages" [value]="lang.id">
        {{ lang.name }}
      </mat-option>
    </mat-select>
  </mat-form-field>
  <div class="fields-container" formArrayName="fields">
    <p>
      Link fields
    </p>
    <ng-container *ngFor="let field of headerData.controls; let i = index;">
      <mat-form-field appearance="fill" [formGroupName]="i">
        <mat-label>{{ incomingFieldNames[i] }}</mat-label>
        <mat-select formControlName="{{incomingFieldNames[i]}}">
          <mat-option *ngFor="let hField of newHeaderFieldsToMap" [value]="hField.value">
            {{ hField.name }}
          </mat-option>
        </mat-select>
      </mat-form-field>
    </ng-container>
  </div>
  <button type="submit" mat-raised-button color="primary">Send</button>
</form>