Angular reactive form binding not working

假如想象 提交于 2019-12-06 15:41:23

there are to make several changes in your code

1.-The employed.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.- the employed.details.component.ts, becomes as

  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)
  }

Finally, when remove the employe you must remove the element in the array

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

see the stackblitz

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!