Angular 7的反应式表单 - 将FormArray中的FormGroup链接到对象
创始人
2024-10-17 00:30:49
0

在Angular 7中,你可以使用反应式表单来链接一个FormArray中的FormGroup到一个对象。下面是一个包含代码示例的解决方法:

首先,在你的组件类中引入必要的模块:

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, FormArray } from '@angular/forms';

然后,在组件类中定义一个FormGroup和一个FormArray:

@Component({
  selector: 'app-your-component',
  templateUrl: './your-component.component.html',
  styleUrls: ['./your-component.component.css']
})
export class YourComponent implements OnInit {
  form: FormGroup;

  ngOnInit() {
    this.form = new FormGroup({
      name: new FormControl(''),
      items: new FormArray([])
    });
  }

  // 用于获取items的FormArray控件
  get itemsForms() {
    return this.form.get('items') as FormArray;
  }

  // 用于向items的FormArray中添加一个新的FormGroup
  addItem() {
    const item = new FormGroup({
      itemName: new FormControl(''),
      itemDescription: new FormControl('')
    });

    this.itemsForms.push(item);
  }

  // 用于从items的FormArray中移除一个FormGroup
  removeItem(index) {
    this.itemsForms.removeAt(index);
  }

  // 用于保存表单数据
  save() {
    console.log(this.form.value);
  }
}

在上面的代码中,我们创建了一个FormGroup来表示整个表单,并在其中定义了一个FormControl来表示名称字段以及一个FormArray来表示items字段。然后,我们定义了三个方法:addItem用于向items的FormArray中添加一个新的FormGroup,removeItem用于从items的FormArray中移除一个FormGroup,以及save用于保存表单数据。

接下来,在你的组件模板中,你可以使用以下代码来绑定表单控件:

在上面的代码中,我们使用formGroup指令将整个表单绑定到form变量,并使用formControlName指令将表单控件绑定到相应的字段。我们还使用formArrayName指令将items的FormArray绑定到itemsForms方法返回的FormArray控件。在ngFor循环中,我们使用formGroupName指令将每个FormGroup绑定到相应的索引位置。

这就是在Angular 7中使用反应式表单链接FormArray中的FormGroup到对象的解决方法。希望对你有帮助!

相关内容

热门资讯

Android Recycle... 要在Android RecyclerView中实现滑动卡片效果,可以按照以下步骤进行操作:首先,在项...
安装apache-beam==... 出现此错误可能是因为用户的Python版本太低,而apache-beam==2.34.0需要更高的P...
Android - 无法确定任... 这个错误通常发生在Android项目中,表示编译Debug版本的Java代码时出现了依赖关系问题。下...
Android - NDK 预... 在Android NDK的构建过程中,LOCAL_SRC_FILES只能包含一个项目。如果需要在ND...
Akka生成Actor问题 在Akka框架中,可以使用ActorSystem对象生成Actor。但是,当我们在Actor类中尝试...
Agora-RTC-React... 出现这个错误原因是因为在 React 组件中使用,import AgoraRTC from “ago...
Alertmanager在pr... 首先,在Prometheus配置文件中,确保Alertmanager URL已正确配置。例如:ale...
Aksnginxdomainb... 在AKS集群中,可以使用Nginx代理服务器实现根据域名进行路由。以下是具体步骤:部署Nginx i...
AddSingleton在.N... 在C#中创建Singleton对象通常是通过私有构造函数和静态属性来实现,例如:public cla...
Alertmanager中的基... Alertmanager中可以使用repeat_interval选项指定在一个告警重复发送前必须等待...