Angular Reactive formArray中的单选按钮-选择数组中的一项

时间:2019-03-28 05:25:35

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

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

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

工作代码可在 StackBlitz 中使用:https://stackblitz.com/edit/angular-reactiveform-radiobutton-in-arrayform

源代码:AppComponent.ts

hashlib.sha256(input()).hexdigest()

源代码:AppComponent.html

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);
  }
}

enter image description here

请协助我如何从N个地址中选择一个地址作为PRIMARY。地址属性“ <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> ”中只有一个应为isPrimary其他项,而所有属性应为true

1 个答案:

答案 0 :(得分:0)

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

<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>

此处是相关部分:

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: [''],
      })
    );
  }

希望这会有所帮助!