Angular Reactive Form Array with Radio Buttons

Han*_*ter 3 angular angular-reactive-forms angular-formbuilder

i have problems with reactive forms and an array of radio buttons.

My Form looks like this:

例子
There is a player in a row and i have to choose the status.

component:

 <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>
Run Code Online (Sandbox Code Playgroud)

The player data comes from an API and status is an array.

ts:

this.myForm = formBuilder.group({
    status: this.formBuilder.array,
    })
Run Code Online (Sandbox Code Playgroud)

My example does not work. I need a json-file as result. (playername + status e.g. present) I can't find a way to implement it. Any hints?

rob*_*ert 5

也许你可以不使用表格来做到这一点。

基本上有一个像这样使用 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>
Run Code Online (Sandbox Code Playgroud)

以及获取所需数据的简单函数:

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

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>
Run Code Online (Sandbox Code Playgroud)

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));
  }
Run Code Online (Sandbox Code Playgroud)

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

新的工作堆栈闪电战

更新第二

正如@Eliseo 建议的那样,您可以在不嵌套 FormArray 的情况下执行此操作。

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

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

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>  
Run Code Online (Sandbox Code Playgroud)

闪电战

第三次更新

如果您有来自 observable 的数据,请考虑以下方法。我正在使用 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, '')
      );
    });
  }
Run Code Online (Sandbox Code Playgroud)

闪电战