Angular Reactive 形式的嵌套动态数组形式 [英] Nested dynamic array forms in Angular Reactive forms

查看:23
本文介绍了Angular Reactive 形式的嵌套动态数组形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组表单,即地址",一旦用户单击添加地址"按钮,就会立即添加一个地址表单,这将是动态的.我用一个问题实现了这个(添加/删除地址工作正常).现在我需要添加一个类似于地址的动态联系电话.

一个地址可能包含一个或多个电话号码,如果用户点击添加电话号码"需要在地址表单中添加新的电话号码表单,则所有地址表单都需要该功能.(即,数组数组 => 地址数组,每个地址包含联系人数组)

StackBlitz 中提供了工作代码:https://stackblitz.com/edit/angular-maexn8

示例代码:

import { Injectable } from '@angular/core';从@angular/forms"导入 { FormBuilder, FormGroup, FormArray, Validators };从'../../model/user'导入{用户};@Injectable()导出类 UpsertUserFormService {公共用户表单:FormGroup;构造函数(私有_fb:FormBuilder){this.userForm = this._fb.group({关系: [],标题: [],名: [],姓: [],地址:this._fb.array([this.addAddressGroup()])});}私有 addAddressGroup(): FormGroup {返回 this._fb.group({街道: [],城市: [],状态: [],PIN码: [],isPrimary: [],联系人:this._fb.array([this.contactsGroup()])});}显示消息(对象:任何){console.log('控制台项目:',obj)}私人联系人组():表单组{返回 this._fb.group({电话号码:['9712345678',[Validators.maxLength(10)]],});}添加地址():无效{this.addressArray.push(this.addAddressGroup());console.log(this.addressArray);}removeAddress(index: number): void {this.addressArray.removeAt(index);}获取地址数组():FormArray {return this.userForm.get('address');}}

请帮助我如何实现动态嵌套数组表单(添加/删除表单).

解决方案

需要根据formGroupformArrays正确声明.

您可以使用this作为参考.

编辑

分叉您的代码:此处.如上所述,保持group/array/controls的顺序

App.component.ts

import { Component } from '@angular/core';从@angular/forms"导入 { FormBuilder, FormGroup, FormArray, Validators };@成分({选择器:'我的应用',templateUrl: './app.component.html',styleUrls: ['./app.component.css']})导出类 AppComponent {name = '角度';公共用户表单:FormGroup;构造函数(私有_fb:FormBuilder){this.userForm = this._fb.group({名: [],姓: [],地址:this._fb.array([this.addAddressGroup()])});}私有 addAddressGroup(): FormGroup {返回 this._fb.group({街道: [],城市: [],状态: [],联系人:this._fb.array([])});}添加地址():无效{this.addressArray.push(this.addAddressGroup());console.log(this.addressArray);}removeAddress(index: number): void {this.addressArray.removeAt(index);}获取地址数组():FormArray {return this.userForm.get('address');}添加联系人(索引):无效{(<FormArray>(<FormGroup>this.addressArray.controls[index]).controls.contacts).push(this.contactsGroup());}私人联系人组():表单组{返回 this._fb.group({联络人: [],电话号码:['9712345678',[Validators.maxLength(10)]],});}addPhoneNumber(index: number): void {this.addressArray[index].contacts.push(this.contactsGroup());console.log(this.addressArray[index].contacts);}}## App.component.html ##

用户创建

<form class="example-form" [formGroup]="userForm"><div class="primary-container"><input matInput placeholder="First Name" value=""formControlName="firstName"><input matInput placeholder="Last Name" value=""formControlName="lastName">

<div class="address-container" *ngFor="let group of addressArray.controls; let i = index;"formArrayName="地址"><div [formGroupName]='i'><input matInput placeholder="Street" value=""formControlName="street"><input matInput placeholder="City" value=""formControlName="city"><input matInput placeholder="State" value="" formControlName="state"><div formArrayName='联系人'><div *ngFor="let subgroup of group.controls.contacts.controls; let idx = index;"[formGroupName]="idx​​"><input matInput placeholder="Contact Person" value="" formControlName="contactPerson"><input matInput placeholder="电话号码" value="" formControlName="phoneNumber">

<button mat-raised-button (click)="addContact(i)">添加更多联系人</button>

<div class="form-row org-desc-parent-margin"><button mat-raised-button (click)="addAddress()">添加更多地址</button>

I'm having a array form namely "address" and this will be a dynamic once the user clicks the "Add Address" button immediately one address form will add. I implemented this with an issue (Add/Remove address works fine). Now I need to add a dynamic contact numbers similar like address.

A address may contain one or more than one phone numbers, if the user clicks "Add Phone number" need to add a new phone number form inside the address form, the functionality will required in all the address forms. (i.e., array of array => array of address and each address contains array of contacts)

Working code is available in StackBlitz: https://stackblitz.com/edit/angular-maexn8

Sample Code:

import { Injectable } from '@angular/core';
import { FormBuilder, FormGroup, FormArray, Validators } from '@angular/forms';
import { User } from '../../model/user';

@Injectable()
export class UpsertUserFormService {

  public userForm: FormGroup;

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

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

  showMessage(obj: any) {
    console.log('Console Item: ',obj)
  }

  private contactsGroup(): FormGroup {
    return this._fb.group({
      phoneNumber: ['9712345678', [Validators.maxLength(10)]], 
    });
  }

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

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

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

}

Kindly assist me how to implement dynamic nested array forms (Add/Remove forms).

解决方案

You need to declare according to the formGroup or formArrays properly.

You can use this as reference.

Edit

Forked your code: here. As mentioned above, keep the group/array/controls in order

App.component.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: [],
      contacts: this._fb.array([])
    });
  }

  addAddress(): void {

    this.addressArray.push(this.addAddressGroup());

    console.log(this.addressArray);
  }

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

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

  addContact(index): void {
    
    (<FormArray>(<FormGroup>this.addressArray.controls[index]).controls.contacts).push(this.contactsGroup());
  }

  private contactsGroup(): FormGroup {
    return this._fb.group({
      contactPerson: [],
      phoneNumber: ['9712345678', [Validators.maxLength(10)]], 
    });
  }

  addPhoneNumber(index: number): void {
    this.addressArray[index].contacts.push(this.contactsGroup());
    console.log(this.addressArray[index].contacts);
  }
}

## App.component.html ##

<h3>Users Creation</h3>

<form class="example-form" [formGroup]="userForm">
	<div class="primary-container">
    <input matInput placeholder="First Name" value="" formControlName="firstName">
    <input matInput placeholder="Last Name" value="" formControlName="lastName">
	</div>
	<div class="address-container" *ngFor="let group of addressArray.controls; let i = index;" formArrayName="address">
		<div [formGroupName]='i'>
			<input matInput placeholder="Street" value="" formControlName="street"> 
      <input matInput placeholder="City" value="" formControlName="city">
      <input matInput placeholder="State" value="" formControlName="state">
    
    <div formArrayName='contacts'>
      <div *ngFor="let subgroup of group.controls.contacts.controls; let idx = index;" [formGroupName]="idx">
        <input matInput placeholder="Contact Person" value="" formControlName="contactPerson">
        <input matInput placeholder="Phone Number" value="" formControlName="phoneNumber">
      </div>
      <button mat-raised-button (click)="addContact(i)">Add more Contacts</button>
    </div>
    </div>
  </div>
  <div class="form-row org-desc-parent-margin">
    <button mat-raised-button (click)="addAddress()">Add more address</button>
  </div>
</form>

这篇关于Angular Reactive 形式的嵌套动态数组形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆