【问题标题】:Angular reactive form binding not working角反应形式绑定不起作用
【发布时间】:2019-05-13 07:42:54
【问题描述】:

我正在尝试在这里创建嵌套的响应式表单:https://stackblitz.com/edit/angular-mgrfbj

这是项目层次结构:

---create company form (hello.component.ts)
    --- company details form (company-details.component.ts)
    --- [
        employee details form (employee-details.component.ts)
        employee details form
        employee details form ...
        ]

对于这样的嵌套表单,我必须使用this video 中给出的ViewProvidersFormGroupDirective

第一个嵌套表单 (company-details.component.ts) 按预期工作

但是在FormArray 中添加*ngFor 的第二种形式没有正确绑定到FormGroupDirective

当您输入公司详细信息并按打印 Json 时,打印的 json 将是正确的。但是当您添加一两个员工时,员工详细信息不会打印在 json 中。

我知道还有其他手动方法可以完成同样的事情,但我正在寻找一个干净的解决方案,无需任何额外功能即可工作。

任何帮助将不胜感激!

提前致谢

【问题讨论】:

  • 您是否注意到 this.fgd 在您的员工详细信息中未定义?
  • 您能多介绍一下“清洁解决方案”吗?

标签: angular angular2-forms angular-reactive-forms


【解决方案1】:

需要对您的代码进行几处更改

1.-使用的.details.component.html

<!---see that is [formGroup], not formGroupName-->
<div [formGroup]="employee">
  <h4 class="row">Employee no. {{index+1}}</h4>
  <div class='col-md-8'>
    <input formControlName="name" placeholder="Name">
  </div>
  <div class='col-md-8'>
    <input formControlName="planet" placeholder="Planet">
  </div>
</div>

2.- 使用的.details.component.ts,变成了

  employee: any;
  @Input() index;
  //inject the ForumGroupDirective in the variable fgd    
  constructor(private fb: FormBuilder,
              private fgd: FormGroupDirective) {}

  ngOnInit() {
    //get the FormArray of "employees"
    const array=(this.fgd.form.get('employees') as FormArray);

    //Simple push to the array
    array.push(this.fb.group({
      name: '',
      planet: ''
      }));
    //the formGroup must be array.at(index)
    this.employee = array.at(this.index)
  }

最后,当移除员工时,你必须移除数组中的元素

  removeEmployee() {
    this.employeesCount -= 1;
    (this.form.get('employees') as FormArray).removeAt(this.employeesCount);
  }

stackblitz

【讨论】:

  • 拯救了我的一天!还更深入地了解了反应形式!非常感谢!
猜你喜欢
  • 2021-11-25
  • 1970-01-01
  • 2020-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-26
  • 2021-02-17
  • 2019-05-26
相关资源
最近更新 更多