带单选按钮的角反应形式数组

时间:2019-06-19 19:57:42

标签: angular angular-reactive-forms angular-formbuilder

我在反应形式和单选按钮数组方面遇到问题。

我的表单如下:

Example
连续有一个玩家,我必须选择状态。

组件:

 <tr *ngFor="let data of player">
        <th>{{data.firstname}} {{data.lastname}}</th>
        <th *ngFor="let stat of status">
        <input type="radio" id="opt1+{{data.id}}" value="{{stat}}" name="option+{{data.id}}" formArrayName="status???"></th>
      </tr>

播放器数据来自API,状态为数组。

ts:

this.myForm = formBuilder.group({
    status: this.formBuilder.array,
    })

我的示例不起作用。 我需要一个json文件作为结果。 (玩家名称+状态,例如当前) 我找不到实现它的方法。 有提示吗?

1 个答案:

答案 0 :(得分:2)

也许您可以不用表格就可以做到。

基本上使用ngModel这样的html设置来设置状态:

<table>
  <tr>
    <th>Firstname</th>
    <th>present</th>
    <th>missing</th>
    <th>apologizes</th>
    <th>unexcused</th>
  </tr>
  <tr *ngFor="let data of player">
    <th>{{data.firstname}} {{data.lastname}}</th>
    <th *ngFor="let stat of status">
      <input type="radio" id="opt1+{{data.id}}" [(ngModel)]="data.status" value="{{stat}}" name="option+{{data.id}}">
    </th>
  </tr>
</table>

还有一个简单的函数来获取所需的数据:

  getJsonResult() {
    alert(JSON.stringify(this.player.map(x => {
      return {
        playername: x.firstname + ' ' + x.lastname,
        status: x.status
      }
    })));
  }

stackblitz上的工作示例。

更新

ReactiveForm方式需要更多代码。首先是一个FormGroup,然后在一个具有播放器的FormArray内。 formArrayName="players"

<form (ngSubmit)="onSubmit()" [formGroup]="playersForm">
  <table border="1">
    <tr>
      <th>Firstname</th>
      <th>present</th>
      <th>missing</th>
      <th>apologizes</th>
      <th>unexcused</th>
    </tr>
    <tr formArrayName="players" *ngFor="let data of playersForm.get('players').controls; let i = index">
      <ng-container [formGroupName]="i">
        <th>
          <input type="text" formControlName="name" readonly>
        </th>
        <th *ngFor="let stat of status">
          <input type="radio" formControlName="status" value="{{stat}}">
        </th>
      </ng-container>
    </tr>
  </table>
  <br>
  <button type="submit">Submit</button>
</form>

Typescript部分将构造并填充数组。

playersForm: FormGroup; constructor(private fb: FormBuilder) { }

  ngOnInit(): void {
    this.playersForm = this.fb.group({
      players: this.fb.array([])
    });

    this.player.forEach(p => {
      (this.playersForm.get('players') as FormArray).push(
        this.addPlayerFormGroup(p.firstname + ' ' + p.lastname, '')
      );
    });
  }

  private addPlayerFormGroup(name?: string, status?: string): FormGroup {
    return this.fb.group({
      name,
      status
    });
  }

  onSubmit() {
    alert(JSON.stringify(this.playersForm.value));
  }

在app.moudule.ts中 import { ReactiveFormsModule } from '@angular/forms';而不是FormsModule。

新工作的stackblitz

第二次更新

如@Eliseo所建议的,您可以在不嵌套FormArray的情况下进行操作。

  ngOnInit(): void {
    this.playersForm = this.fb.array([]);

    this.player.forEach(p => {
      this.playersForm.push(
        this.addPlayerFormGroup(p.firstname + ' ' + p.lastname, '')
      );
    });
  }

html:

<tr *ngFor="let fg of playersForm.controls; index as i">        
<td>
  <input type="text" [formControl]="fg.get('name')" readonly>
</td>
<td *ngFor="let stat of status">

  <input type="radio" id="opt1+{{player[i].id}}" value="{{stat}}" name="option+{{player[i].id}}" 
    [formControl]="fg.get('status')">
</td>  

Stackblitz

更新第3

如果您有可观察的数据,请考虑以下方法。我正在使用SWAPI来获取一些数据。一旦收到数据。您可以将原始数据映射为所需的格式,然后调用一种方法来填充FormArray。

  ngOnInit(): void {
    this.playersForm = this.fb.array([]);
    let counter = 0;
    const apiUrl = 'https://swapi.co/api/people';    
    this.http.get(apiUrl).subscribe((peoples: any) => {
      this.player = peoples.results.map(p => {
        return {
          id: ++counter,
          name: p.name,
          staus: null
        }
      })
      this.populateForm();
    });
  }

  private populateForm() {
    this.player.forEach(p => {
      this.playersForm.push(
        this.addPlayerFormGroup(p.name, '')
      );
    });
  }

Stackblitz