【问题标题】:Radio button in Angular Reactive formArray - Select one item in an arrayAngular Reactive formArray中的单选按钮-选择数组中的一项
【发布时间】:2019-08-18 19:35:42
【问题描述】:

我有一个名为“地址”的表单数组,这将是一个动态的,一旦用户立即单击“添加地址”按钮,就会添加一个地址表单。每个地址表单都有一个单选按钮 - 用户需要选择任何具有 PRIMARY 地址的地址(即,用户需要选择数组中的一项)。

我参考了以下问题,但它现在完全满足了我的要求 Angular formArray radio buttons 在上述问题中,每个项目都有一组单选按钮(即项目内的选择)

StackBlitz 中提供了工作代码:https://stackblitz.com/edit/angular-reactiveform-radiobutton-in-arrayform

源代码:AppComponent.ts

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
  public userForm: FormGroup;

  constructor(private _fb: FormBuilder) {
    this.userForm = this._fb.group({
      firstName: [],
      lastName: [],
      address: this._fb.array([this.addAddressGroup()])
    });
  }

  private addAddressGroup(): FormGroup {
    return this._fb.group({
      street: [],
      city: [],
      state: [],
      isPrimary: []
    });
  }

  get addressArray(): FormArray {
    return <FormArray>this.userForm.get('address');
  }

  addAddress(): void {
    this.addressArray.push(this.addAddressGroup());
  }

  removeAddress(index: number): void {
    this.addressArray.removeAt(index);
  }
}

源码:AppComponent.html

<form class="example-form" [formGroup]="userForm">
  <div>
    <mat-card class="example-card">
      <mat-card-header>
        <mat-card-title>Users Creation</mat-card-title>
      </mat-card-header>
      <mat-card-content>
        <div class="primary-container">
          <mat-form-field>
            <input matInput placeholder="First Name" value="" formControlName="firstName">
          </mat-form-field>
          <mat-form-field>
            <input matInput placeholder="Last Name" value="" formControlName="lastName">
          </mat-form-field>
        </div>
        <div formArrayName="address">
          <div class="address-container" *ngFor="let group of addressArray.controls; let i = index;"
            [formGroupName]="i">
            <fieldset>
              <legend>
                <h3>Address: {{i + 1}}</h3>
              </legend>
              <mat-radio-button class="example-radio-button" value="true" checked="true" formControlName="isPrimary">
                Primary
              </mat-radio-button>
              <div>
                <mat-form-field>
                  <input matInput placeholder="Street" value="" formControlName="street">
                </mat-form-field>
                <mat-form-field>
                  <input matInput placeholder="City" value="" formControlName="city">
                </mat-form-field>
                <mat-form-field>
                  <input matInput placeholder="State" value="" formControlName="state">
                </mat-form-field>
              </div>
            </fieldset>
          </div>
        </div>
        <div class="form-row org-desc-parent-margin">
          <button mat-raised-button (click)="addAddress()">Add more address</button>
        </div>
      </mat-card-content>
    </mat-card>
  </div>
</form>
<mat-card class="pre-code">
  <mat-card-header>
    <mat-card-title>Users Information</mat-card-title>
  </mat-card-header>
  <mat-card-content>
    <pre>{{userForm.value | json}}</pre>
  </mat-card-content>
</mat-card>

请帮助我如何从 N 个地址中选择一个地址作为 PRIMARY。只有一个地址属性“isPrimary”应该是true,其他项目都应该是false

【问题讨论】:

  • 我认为您应该这样做,当单选按钮选中事件触发时,您必须传入 ts 文件并使其仅选中并执行添加地址的循环并将其他收音机标记为未选中。跨度>
  • @PareshGami - 是的,但我正在等待是否有任何直接的方法,或者其他代码明智的实现是唯一的方法。
  • 我也有类似的问题。你是如何解决这种情况的? @B.Balamanigandan

标签: javascript angular radio-button angular-reactive-forms formarray


【解决方案1】:

在一个新项目中,我仅使用材质组件就实现了这一点,而不涉及事件/循环...... 关键是使用 mat-radio-groupname 属性来使无线电组的所有迭代都表现为一个。

<mat-radio-group [formControl]="userForm.controls.primary" name="primary">

我还为“isPrimary”检查使用了不同的方法。我没有在每个地址实例中使用布尔属性,而是在用户模型中使用了一个属性“主地址索引”,因此当您单击单选按钮时,主字段的值将使用当前元素的索引进行更新([value]="i")

<mat-radio-button [value]="i">Primary</mat-radio-button>

这是我的完整表格

<form [formGroup]="userForm" (ngSubmit)="onSubmit()">
    name
    <input formControlName="name" /><br>
    email
    <input formControlName="email" /><br>
    VAT
    <input formControlName="VAT" /><br>

    <button (click)="addNewAddress()">Add new address</button><br>

    <div formArrayName="addresses">
        <div *ngFor="let address of userForm.get('addresses').controls; let i=index">
            <h3>ADDRESS {{i+1}}: </h3>
            primary
            <mat-radio-group [formControl]="userForm.controls.primary" name="primary">
                <mat-radio-button [value]="i">Primary
                </mat-radio-button>
            </mat-radio-group>


            <div [formGroupName]="i">
                street
                <input formControlName="street" /><br>
                city
                <input formControlName="city" /><br>
                country
                <input formControlName="country" /><br>
                zip
                <input formControlName="zip" /><br>

                <button (click)="deleteAddress(i)">
                    Delete <address></address>
                </button>
            </div>
        </div>
    </div>
    <button type="submit" [disabled]="userForm.pristine || !userForm.valid">Save</button>
</form>

这里是ts相关部分:

initForm() {
   this.detailForm = this.fb.group({
        name: ['', Validators.required],
        VAT: ['', Validators.required],
        fiscalCode: ['', Validators.required],
        legalEntity: ['',],
        email: ['', Validators.email],
        primary: [0, Validators.required], //when creating a new customer, set first address as primary
        addresses: this.fb.array([]),
      });
}

addNewAddress(addr: Address): void {
    let control = <FormArray>this.detailForm.controls.addresses;
    control.push(
      this.fb.group({
        street: ['', Validators.required],
        city: ['', Validators.required],
        country: ['', Validators.required],
        zip: [''],
      })
    );
  }

希望这能有所帮助!

【讨论】:

  • 你测试过你的代码吗,@Geko?如果是这样,你能提供有效的 StackBlitz 吗?
猜你喜欢
  • 1970-01-01
  • 2022-01-13
  • 1970-01-01
  • 2019-11-28
  • 1970-01-01
  • 2021-02-15
  • 2017-07-24
  • 2018-06-23
  • 2020-08-18
相关资源
最近更新 更多