簡體   English   中英

Angular 反應式 Forms FormArray - 無法分配第二個 FormGroup 元素

[英]Angular Reactive Forms FormArray - cannot assign second FormGroup element

我正在與反應式 Forms 和嵌套的 FormArray 戰斗。 我正在開發應用程序以向具有多個地址的客戶顯示。 FormArray 應該保存多個地址並使用 *ngFor 我想向用戶展示它們。

一切正常,除了我無法將更多它們添加到 FormArray(地址)即使我在數組中指定了 2 個元素,我仍然只分配了一個。

我的代碼有什么問題?

地址.component.ts

 import { Component, OnInit } from '@angular/core'; import { ClientsService } from '../../../shared/clients.service'; import { FormArray } from '@angular/forms'; @Component({ selector: 'app-address', templateUrl: './address.component.html', styleUrls: ['./address.component.css'] }) export class AddressComponent implements OnInit { constructor(public clientService: ClientsService) { } get Addresses(): FormArray{ return <FormArray>this.clientService.clientForm.get('Addresses'); } ngOnInit(): void {} }

客戶服務.ts

 import { Injectable } from '@angular/core'; import { FormBuilder, FormGroup, FormArray } from '@angular/forms'; @Injectable({ providedIn: 'root' }) export class ClientsService { constructor(private fb: FormBuilder, private http: HttpClient) { } clientForm = this.buildClientData(); initializeFormGroup() { this.clientForm.patchValue({ Id: 0, CompId: null, NIP: null, ClientRelation: '', CompanyName: '', BusinessType: '', UsName: '', Addresses: [{ Id: 0, Type: 'Company', Country: '', Wojewodztwo: '', Powiat: '', Gmina: 'testo', City: '', StreetName: '', StreetNo: '', ApartmentNo: '', PostalCode: '', PostalCity: '' }, { Id: 1, Type: 'Accomodation', Country: '', Wojewodztwo: '', Powiat: '', Gmina: 'testo', City: '', StreetName: '', StreetNo: '', ApartmentNo: '', PostalCode: '', PostalCity: '' }, ], Phone: '', Active: false, Debtor: false, Poa: '', PoaPayment: '' }); console.log(this.clientForm); } buildClientData(): FormGroup { return this.fb.group ({ Id: 0, CompId: null, NIP: null, ClientRelation: '', CompanyName: '', BusinessType: '', UsName: '', Addresses: this.fb.array([this.buildClientAddress()]), Phone: '', Active: false, Debtor: false, Poa: '', PoaPayment: '' }); } buildClientAddress(): FormGroup { return this.fb.group({ Id: null, Type: '', Country: '', Wojewodztwo: '', Powiat: '', Gmina: '', City: '', StreetName: '', StreetNo: '', ApartmentNo: '', PostalCode: '', PostalCity: '' }); } }

您被添加了一個 object 到 buildClientAddress 的表單組。 如果您添加兩套 object,您將獲得另一套。

如果您希望這是動態的,則必須在前端提供一些按鈕,以便您將在該按鈕操作下提供您的邏輯。

addItem(): void {
  this.items = this.orderForm.get('items') as FormArray;
  this.items.push(this.createItem());
}

createItem(): FormGroup {
  return this.formBuilder.group({
    name: '',
    description: '',
    price: ''
  });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM