Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/434.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 角度反应式阵列中的单选按钮-在阵列中选择一项_Javascript_Angular_Radio Button_Angular Reactive Forms_Formarray - Fatal编程技术网

Javascript 角度反应式阵列中的单选按钮-在阵列中选择一项

Javascript 角度反应式阵列中的单选按钮-在阵列中选择一项,javascript,angular,radio-button,angular-reactive-forms,formarray,Javascript,Angular,Radio Button,Angular Reactive Forms,Formarray,我有一个表格,即“地址”,这将是一个动态的,一旦用户点击“添加地址”按钮,一个地址表将立即添加。每个地址表单都有一个单选按钮-用户需要选择任何一个具有主地址的地址(即,用户需要在数组中选择一个项目) 我提出了以下问题,但现在完全满足了我的要求 在上述问题中,每个项目都有一组单选按钮(即项目内的选择) 工作代码可在StackBlitz中找到: 源代码:AppComponent.ts import { Component } from '@angular/core'; import { FormBu

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

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

工作代码可在StackBlitz中找到:

源代码: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);
  }
}
从'@angular/core'导入{Component};
从“@angular/forms”导入{FormBuilder、FormGroup、FormArray、Validators};
@组成部分({
选择器:“我的应用程序”,
templateUrl:“./app.component.html”,
样式URL:['./app.component.css']
})
导出类AppComponent{
名称='角度';
公共用户表单:FormGroup;
构造函数(私有_fb:FormBuilder){
this.userForm=this.\u fb.group({
名字:[],
姓氏:[],
地址:this.\u fb.array([this.addAddressGroup()]))
});
}
私有addAddressGroup():FormGroup{
将此返回。\u fb.group({
街道:[],
城市:[],
国家:[],
一级:[]
});
}
获取addressArray():FormArray{
返回此.userForm.get('address');
}
addAddress():void{
this.addressArray.push(this.addAddressGroup());
}
removeAddress(索引:编号):void{
this.addressArray.removeAt(索引);
}
}
源代码: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>

用户创建
地址:{i+1}
主要的,重要的
添加更多地址
用户信息
{{userForm.value | json}}


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

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

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

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

Primary
这是我的全部表格

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


名称

电子邮件
增值税
添加新地址
地址{i+1}}: 主要的,重要的 主要的,重要的 街道
城市
国家
拉链
删除 拯救
以下是ts的相关部分:

initForm(){
this.detailForm=this.fb.group({
名称:['',验证器。必需],
增值税:['',验证器。必需],
财务代码:['',验证器。必需],
法律性:['',],
电子邮件:['',验证器。电子邮件],
主:[0,Validators.required],//创建新客户时,将第一个地址设置为主地址
地址:this.fb.array([]),
});
}
addNewAddress(addr:Address):无效{
让control=this.detailForm.controls.addresses;
控制按钮(
本集团({
街道:['',验证器。必需],
城市:['',验证器。必填],
国家:['',验证器。必填],
邮编:[''],
})
);
}

希望这能有所帮助

我想你应该喜欢,当单选按钮选中事件触发时,您必须在ts文件中传入,使其仅被选中,并对添加的地址执行循环,并将其他单选标记为未选中。@PareshGami-是的,但我正在等待是否有任何直接的方法,或者以其他方式代码实现是唯一的方法。我也有类似的问题。你是如何解决这种情况的@巴拉曼尼:你有没有测试过你的代码,@Geko?如果是这样,你能提供有效的StackBlitz吗?
<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: [''],
      })
    );
  }