简体   繁体   English

FormArray 无法在我的反应式表单上打印

[英]FormArray does not print on my Reactive Form

I'm starting at Angular and I'm having a really hard time setting a FormArray inside my form.我从 Angular 开始,我很难在表单中设置 FormArray。 In summary what I did was:总之,我所做的是:

  • Create 2 forms: the main (valForm) and another one created dynamically (holidaysForm).创建2个forms:主(valForm)和另一个动态创建(holidaysForm)。
  • Copy the values of the second form to an Array.将第二种形式的值复制到一个数组。
  • Load the values of the Array into a FormArray.将 Array 的值加载到 FormArray 中。

Follow the codes:遵循以下代码:

.ts .ts

let group = {}
    this.holidaysForm = new FormGroup(group);

    this.valForm = fb.group({
      dentistId: [null, Validators.required],
      initialHour: [null, Validators.required],
      endHour: [null, Validators.required],
      numberOfHolidays: [null],
      appointmentsInterval: [null, Validators.required],
      year: [null, Validators.required],
      workDays: this.buildDays(),
      holidays: this.buildHolidays()
    });

  buildDays() {
    const values = this.workDays.map(v => new FormControl(false));    
    return this.fb.array(values);
  }

  buildHolidays() {
    if (typeof this.valForm !== 'undefined') {
      let teste = Object.assign({}, this.holidaysForm.value);
      this.holidays = new Array();
      Object.values(teste).forEach((v) => {
        this.holidays.push(v);
      })
      console.log(this.holidays);
      const values = this.holidays.map((v)=> new FormControl(v));      
      return this.fb.array(values);
    }
  }

  dynamicForm(val) {
    if (val > 365) {
      val = 365;
      this.valForm.patchValue({
        numberOfHolidays: 365
      })
    }
    const val_plus_one = parseInt(val) + 1
    let i: number = val_plus_one;
    if (i < this.oldNumber) {
      do {
        this.holidaysForm.get('holiday' + i.toString()).setValue(null);
        this.holidaysForm.removeControl('holiday' + i.toString());
        i++
      } while (i <= this.oldNumber)
    }
    const numbers = Array(val).fill(val, 0, 365).map((_, idx) => idx + 1)
    numbers.forEach((num) => {
      const fc = new FormControl('', FormValidations.Calendar(this.valForm.get('year').value));
      this.holidaysForm.addControl('holiday' + num.toString(), fc)
    })
    this.numberOfHolidays = numbers;
    this.oldNumber = val;
  }

.html .html

                        <div class="col-md-4 mda-form-group">
                            <input class="mda-form-control" type="number" min="0" max="365"
                                formControlName="numberOfHolidays"
                                (change)="dynamicForm(valForm.get('numberOfHolidays').value)" />
                            <label>Total de Feriados</label>
                        </div>
                        <div [formGroup]="holidaysForm">
                            <div class="mda-form-group" *ngFor="let num of numberOfHolidays">
                                <input class="mda-form-control" type="date" formControlName="holiday{{num}}" />
                                <label>Feriado {{num}}</label>
                                <app-error-msg [control]="holidaysForm.get('holiday'+num)" label="Feriado">
                                </app-error-msg>
                            </div>
                        </div>

In theory the code works well and without errors, the problem is that the result is always this:从理论上讲,代码运行良好且没有错误,问题是结果总是这样:

Main Form主表格

  Valores: 
 {
  "dentistId": null,
  "initialHour": null,
  "endHour": null,
  "numberOfHolidays": 3,
  "appointmentsInterval": null,
  "year": null,
  "workDays": [
    false,
    false,
    false,
    false,
    false,
    false,
    false
  ],
  "holidays": null
}

Holiday Form假期表格

 {
  "holiday1": "2020-01-01",
  "holiday2": "2020-03-01",
  "holiday3": "2020-02-01"
}

Does anyone have any idea what I might be doing wrong?有谁知道我可能做错了什么? Thankful,谢天谢地,

The problem seems to be you are using holidaysForm before you ever put values in it.问题似乎是您在将值放入其中之前就使用了holidayForm。 So at the point where you are creating the object to loop through to create your array, that object will have no properties.因此,在您创建 object 以循环创建阵列时,object 将没有任何属性。

 buildHolidays() {
if (typeof this.valForm !== 'undefined') {
  let teste = Object.assign({}, this.holidaysForm.value);   // this line
  this.holidays = new Array();
  Object.values(teste).forEach((v) => {
    this.holidays.push(v);
  })
  console.log(this.holidays);
  const values = this.holidays.map((v)=> new FormControl(v));      
  return this.fb.array(values);
}

} }

I would figure out how to get values to use in this method to make it all work.我会弄清楚如何获取在此方法中使用的值以使其全部正常工作。 And remember, you can always add a formArray after the creation of your original formgroup via group.addControl('controlName', myFormArray);请记住,您始终可以在创建原始表单组后通过group.addControl('controlName', myFormArray);

Best of luck, and as always Happy Coding祝你好运,一如既往的快乐编码

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

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