【问题标题】:Angular Reactive form formArray can't insert control based on indexAngular Reactive表单formArray无法插入基于索引的控件
【发布时间】:2020-08-29 09:26:33
【问题描述】:

这是我的表格:

  this.addForm = this.formBuilder.group({
    details: this.formBuilder.array([]),
  });

我正在调用这个函数来推送控制

 nestedFormGroupDetails(control) {
    control.push(
      this.formBuilder.group({
        name: ['', [Validators.required]],
        age: ['', [Validators.required]]
      }));

    **// based on scenario, I want to insert new control. ex. occupation
    this.detailsFormArray.insert(0, [...])  // how to add abstract control here**
  }

 get detailsFormArray() {
    return this.addForm.get('details') as FormArray
 }

请建议我是否以正确的方式进行操作,还请建议我如何在特定索引中插入/推送新控件,例如索引 0 提前致谢

【问题讨论】:

    标签: html angular typescript angular-forms angular-formbuilder


    【解决方案1】:

    你可以有一个 FormControls 的 FormArray 或一个 FormGroups 的 FormArray (*)

    //this insert a new FormControl in an Array of FormControls
    this.detailsFormArray.insert(0,new FormControl())
    
    //this insert a new FormControl in an Array of FormControls
    this.detailsFormArray.insert(0,new FormGroup({
          prop1:new FormControl(),
          prop2:new FormControl(),
       }))
    //or in steps
    const group=new FormGroup({
       prop1:new FormControl(),
       prop2:new FormControl(),
    })
    this.detailsFormArray.insert(0,group)
    

    使用 FormBuilder

    this.detailsFormArray.insert(0,this.fb.control())
    
    //this insert a new FormControl in an Array of FormControls
    this.detailsFormArray.insert(0,this.fb.group({
          prop1:[],
          prop2:[]
       }))
    

    (*)

    • FormControls 的 FormArray.value 为您提供了一个数组 字符串/数字等,例如[0,1,2]
    • FormGroups 的 FormArray.value 为您提供对象数组,例如 [{id:1,name:'name1'},{id:2,name:'name2'}]

    【讨论】:

    • 非常感谢您的回复。我正在尝试使用 FormBuilder。但是当我运行它 ngOnInIt() 时它会抛出错误:错误错误:找不到带有路径的控件:'detailsFormArray-> 0 -> 占用'`this.detailsFormArray.insert(0,this.formBuilder.group({占用:[ ] }))`
    • 在你的 .html 表单中放入 *ngIf:<form *ngIf="addForm" [formGroup]="addForm">.. 通常错误是在很早的 Angular 中引起的,因为表单一开始是空的
    • 感谢您的回答。使用 ngIf 指令,抛出相同的错误,意味着它仍然是相同的。
    猜你喜欢
    • 2017-10-11
    • 2018-12-22
    • 2018-07-15
    • 2023-01-23
    • 2020-07-24
    • 2019-01-31
    • 1970-01-01
    • 1970-01-01
    • 2018-12-22
    相关资源
    最近更新 更多