简体   繁体   English

Angular 8 FormArray 索引数据未更新

[英]Angular 8 FormArray index data is not updating

I'm trying to create dynamic from groups based on initial data with filled content and add/remove from groups.我正在尝试根据带有填充内容的初始数据从组创建动态并从组中添加/删除。 Unfortunately it is not working.不幸的是它不起作用。

Expected behavior is,预期的行为是,

  • Coutry dropdown would be loaded with data and highlighted with selected value which is working fine already. Coutry 下拉列表将加载数据,并使用已正常工作的选定值突出显示。
  • Selected country states dropdown data should be loaded by default with selected value from initial data stateCode and when changing the country too which is not working currently.默认情况下,选定的国家/地区下拉数据应使用初始数据stateCode选定值加载,并且在更改当前不起作用的国家/地区时。
  • While clicking the add button, by default "United states" country and respective states data should be loaded.单击添加按钮时,默认情况下应加载“美国”国家和相应的州数据。 States dropdown should be selected by default with "--select--".默认情况下,应使用“--select--”选择状态下拉列表。

Note: All data will be coming from API.注意:所有数据都将来自 API。 Testing purpose I have added static objects for Countries and States.测试目的我为国家和国家添加了静态对象。

在此处输入图片说明

Here my attempt这是我的尝试

https://stackblitz.com/edit/angular-8-app-example-fkjzfe-wekubn?file=src%2Fapp%2Fapp.component.ts https://stackblitz.com/edit/angular-8-app-example-fkjzfe-wekubn?file=src%2Fapp%2Fapp.component.ts

Current behaviour demo当前行为演示

https://angular-8-app-example-fkjzfe.stackblitz.io/ https://angular-8-app-example-fkjzfe.stackblitz.io/

HTML HTML

  <form [formGroup]='entityForm'>
              <div formArrayName="optionGroups" class="ui-g ui-g-12 ui-g-nopad " >
                <div  style="width: 100%;
    display: flex; margin-bottom:10px" class="ui-g  ui-g-12 ui-g-nopad " *ngFor="let item of entityForm.controls['optionGroups'].controls; let $index=index" [formGroup]="item">        
                  <div class="ui-md-4">                   
                    <label class="mandatory"
                  >Country
                  <span class="colon"></span>
                </label>
                <select formControlName="country" class="ui-inputtext" (change)="onCountryChange(entityForm.controls['optionGroups'].controls[$index].controls['country'].value, $index)" > 
                  <option>--Select--</option>
                  <option *ngFor="let c of countries" [ngValue]="c.countryCode">{{c.country}}</option>                 
                </select>
              </div>
              <div class="ui-md-4">

                <label class="lbl-hidden"> State </label>
                <select formControlName="state" class="ui-inputtext"> 
                  <option>--Select--</option>
                  <option *ngFor="let state of states[entityForm.controls['optionGroups'].controls[$index].controls['country'].value]" value="state.code">{{state.state}}</option>
              </select>
              </div>
              <div class="ui-md-3">
                <label class="lbl-hidden"> Number </label>
                <input
                  type="text"
                  pInputText
                  class="form-control"
                  formControlName="place"    
                />
                </div>
                <div class="ui-md-1">
                 
                  <button (click)='removeOptionGroup(i)'  style="min-width: auto;"  pButton icon="fa fa-minus">Remove</button>
                </div>
                </div>
              </div>
            </form>        
            <button class="add-remove-btn" pButton (click)='addOptionGroup()' icon="fa fa-plus">Add</button>` 

TS TS

import { Component, OnInit, ViewChild } from '@angular/core'

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit  {
  public countryOptions:any = [];
  public stateOptions:any = [];

  public countries = [];
  public states = [];

  public entityForm: FormGroup;

constructor(private fb: FormBuilder) {
  this.entityForm = this.fb.group({
    optionGroups : this.fb.array([]),
});

this.countries = this.countryOptions
this.states=[];
}


public addOptionGroup(){

  const fa = this.entityForm.controls["optionGroups"] as FormArray;
   //fa.setValue("--Select--");
  fa.push(this.newOptionGroup());


  }

  public removeOptionGroup(index: number){

    const fa = this.entityForm.controls["optionGroups"] as FormArray;
  
    fa.removeAt(index);
  
    }

    onCountryChange(selectedCountry: string , formIndex : number) : void {
      this.states[selectedCountry] = this.getStates(selectedCountry)
    }

    private newOptionGroup() {
      return new FormGroup({          
          country: new FormControl("--select--"),
          state: new FormControl("--select--"),
          place: new FormControl("GGG"),

      });
  }


  getStates(selectedCountry) {
    //API call

    switch(selectedCountry) {
      case "US" : 
        this.stateOptions =[
      {id: 14, state: "Alabama", code: "AL", countryCode: "US"},
      {id: 15, state: "Alaska", code: "AK", countryCode: "US"},
      {id: 17, state: "Arizona", code: "AZ", countryCode: "US"},
      {id: 18, state: "Arkansas", code: "AR", countryCode: "US"},
      {id: 19, state: "California", code: "CA", countryCode: "US"}
      ]
      break;

     case  "CA" :
       this.stateOptions =[{id: 37, state: "Marshall Islands", code: "MH", countryCode: "CA"},
      {id: 4, state: "New Brunswick", code: "NB", countryCode: "CA"},
      {id: 5, state: "Newfoundland and Labrador", code: "NL", countryCode: "CA"},
      {id: 53, state: "Northern Mariana Islands", code: "MP", countryCode: "CA"},
      {id: 6, state: "Northwest Territories", code: "NT", countryCode: "CA"}]
      break;    
    default: 
     this.stateOptions =[
      {id: 14, state: "Alabama", code: "AL", countryCode: "US"},
      {id: 15, state: "Alaska", code: "AK", countryCode: "US"},
      {id: 17, state: "Arizona", code: "AZ", countryCode: "US"},
      {id: 18, state: "Arkansas", code: "AR", countryCode: "US"},
      {id: 19, state: "California", code: "CA", countryCode: "US"}
      ]
      break;
  }
    return this.stateOptions;

   }

   initFormArray(initForm:any) {
    const formArray = this.entityForm.get('optionGroups') as FormArray;
    initForm.map((item, index) => {
      formArray.push(this.createForms(item, index));
    });
    this.entityForm.setControl('optionGroups', formArray);
   }

   createForms(adresse, index): FormGroup {
   
    let formGroup: FormGroup = new FormGroup(
      {
        country: new FormControl(adresse.countryCode),
        state: new FormControl(adresse.stateCode),
        place: new FormControl(adresse.fileNumber)
      }
    );
 this.onCountryChange(adresse.select1, index)
    return formGroup;
  }


  
 getAllCountries() {
   //API call
   this.countries = [{"country":"United States","countryCode":"US"},{"country":"Canada","countryCode":"CA"}]
 }
  

  ngOnInit() {
    this.getAllCountries()
    const initData = [
      {countryCode: "US", stateCode: "AZ", fileNumber: "AAA"},
      {countryCode: "CA", stateCode: null, fileNumber: null}
    ]

    this.initFormArray(initData)
  }

}

I symplified you scripts and seems work as due.我对你的脚本进行了简化,似乎工作正常。 But it's not finish - all may be done much more pretty.但这还没有结束——一切都可能做得更漂亮。 Pay attention to the formation html part - [formGroupName]="i" and how to work with formArray variable.注意格式 html 部分 - [formGroupName]="i" 以及如何使用 formArray 变量。

//html
<form [formGroup]="entityForm">
  <div formArrayName="optionGroups" class="ui-g ui-g-12 ui-g-nopad">
    <ng-container *ngFor="let item of optionGroups.controls; let i = index;" [formGroupName]="i">
      <div style="width: 100%; display: flex; margin-bottom:10px" class="ui-g  ui-g-12 ui-g-nopad">
        <div class="ui-md-4">
          <label class="mandatory">Country <span class="colon"></span></label>
          <select 
            formControlName="country"
            class="ui-inputtext" 
            (change)="onCountryChange(item.get('country').value, i)" 
            > 
            <option>--Select--</option>
            <option *ngFor="let c of countries" [ngValue]="c.countryCode">{{c.country}}</option>                 
          </select>
        </div>

        <div class="ui-md-4">
          <label class="lbl-hidden"> State </label>
          <select formControlName="state" class="ui-inputtext"> 
            <option>--Select--</option>
            <option *ngFor="let state of getStates(item.controls['country'].value)" [ngValue]="state.code">{{state.state}}</option>
          </select>
        </div>

        <div class="ui-md-3">
          <label class="lbl-hidden"> Number </label>
          <input
            type="text"
            pInputText
            class="form-control"
            formControlName="place"    
          />
        </div>
        <div class="ui-md-1">     
          <button (click)='removeOptionGroup(i)'  style="min-width: auto;"  pButton icon="fa fa-minus">Remove</button>
        </div>
      </div>
    </ng-container>
  </div>
</form>
<button class="add-remove-btn" pButton (click)='addOptionGroup()' icon="fa fa-plus">Add</button>

//ts
public countryOptions:any = [];
  public stateOptions:any = [];

  public countries = [];
  public states = [];

  public entityForm: FormGroup;
  public optionGroups: FormArray;

  constructor(
    private fb: FormBuilder
    ) {}

  ngOnInit() {
    this.entityForm = this.fb.group({
      optionGroups : this.fb.array([])
    });

    this.optionGroups = this.entityForm.get('optionGroups') as FormArray;

    this.getAllCountries();
    const initData = [
      {countryCode: "US", stateCode: "AZ", fileNumber: "AAA"},
      {countryCode: "CA", stateCode: null, fileNumber: null}
    ]

    this.initFormArray(initData)
  }


  public addOptionGroup(){
    const fa = this.entityForm.get('optionGroups') as FormArray;
    //fa.setValue("--Select--");
    fa.push(this.newOptionGroup());
  }

  public removeOptionGroup(index: number){

      const fa = this.entityForm.controls["optionGroups"] as FormArray;
    
      fa.removeAt(index);
    
      }

  onCountryChange(selectedCountry: string , formIndex : number) : void {
    console.log(selectedCountry);
    this.states[selectedCountry] = this.getStates(selectedCountry)
  }

  private newOptionGroup() {
    return new FormGroup({          
        country: new FormControl("--select--"),
        state: new FormControl("--select--"),
        place: new FormControl("GGG"),

    });
  }


  getStates(selectedCountry) {
    //API call

      switch(selectedCountry) {
        case "US" : 
          this.stateOptions =[
        {id: 14, state: "Alabama", code: "AL", countryCode: "US"},
        {id: 15, state: "Alaska", code: "AK", countryCode: "US"},
        {id: 17, state: "Arizona", code: "AZ", countryCode: "US"},
        {id: 18, state: "Arkansas", code: "AR", countryCode: "US"},
        {id: 19, state: "California", code: "CA", countryCode: "US"}
        ]
        break;

      case  "CA" :
        this.stateOptions =[{id: 37, state: "Marshall Islands", code: "MH", countryCode: "CA"},
        {id: 4, state: "New Brunswick", code: "NB", countryCode: "CA"},
        {id: 5, state: "Newfoundland and Labrador", code: "NL", countryCode: "CA"},
        {id: 53, state: "Northern Mariana Islands", code: "MP", countryCode: "CA"},
        {id: 6, state: "Northwest Territories", code: "NT", countryCode: "CA"}]
        break;    
      default: 
      this.stateOptions =[
        {id: 14, state: "Alabama", code: "AL", countryCode: "US"},
        {id: 15, state: "Alaska", code: "AK", countryCode: "US"},
        {id: 17, state: "Arizona", code: "AZ", countryCode: "US"},
        {id: 18, state: "Arkansas", code: "AR", countryCode: "US"},
        {id: 19, state: "California", code: "CA", countryCode: "US"}
        ]
        break;
    }
    return this.stateOptions;
  }

  initFormArray(initForm:any) {
    console.log(initForm);
    initForm.map((item, index) => {
      this.optionGroups.push(this.createForms(item, index));
    });
  }

  createForms(adresse, index): FormGroup {   
    const formGroup = new FormGroup({
        country: new FormControl(adresse.countryCode),
        state: new FormControl(adresse.stateCode),
        place: new FormControl(adresse.fileNumber)
      });
    this.onCountryChange(adresse.select1, index);
  return formGroup;
  }

  getAllCountries() {
    //API call
    this.countries = [{"country":"United States","countryCode":"US"},{"country":"Canada","countryCode":"CA"}]
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM