Angular响应式表单中嵌套表单的问题。如何在ts文件中声明并在html文件中访问字段。
创始人
2024-10-30 08:00:45
0

在Angular响应式表单中,可以使用FormGroup和FormControl来声明和访问嵌套表单字段。以下是一个示例解决方法:

在ts文件中声明嵌套表单字段:

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

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

  nestedForm: FormGroup; // 声明嵌套表单的FormGroup

  constructor() { }

  ngOnInit() {
    this.nestedForm = new FormGroup({
      firstName: new FormControl('', Validators.required), // 在嵌套表单中声明字段
      lastName: new FormControl('', Validators.required),
      address: new FormGroup({
        street: new FormControl('', Validators.required),
        city: new FormControl('', Validators.required),
        state: new FormControl('', Validators.required),
        zip: new FormControl('', Validators.required)
      })
    });
  }

  submitForm() {
    console.log(this.nestedForm.value); // 打印嵌套表单的值
  }

}

在html文件中访问嵌套表单字段:

First Name is required!
Last Name is required!
Street is required!
City is required!
State is required!
Zip is required!

以上代码示例中,我们使用FormGroup和FormControl来声明和访问嵌套表单字段,使用formGroup和formControlName指令在html文件中绑定字段。在submitForm方法中,我们可以通过this.nestedForm.value获得嵌套表单的值。

相关内容

热门资讯

据相关数据显示!小程序微乐游戏... 据相关数据显示!小程序微乐游戏辅助,原来真的有辅助挂(有挂实锤)-哔哩哔哩该软件可以轻松地帮助玩家将...
据统计!人皇大厅控制牌型,竟然... 据统计!人皇大厅控制牌型,竟然有挂辅助平台(有挂实锤)-哔哩哔哩1、人皇大厅控制牌型辅助软件下载优化...
现场直击!打哈儿辅助,竟然是有... 现场直击!打哈儿辅助,竟然是有辅助平台(有挂实锤)-哔哩哔哩1)打哈儿辅助辅助插件:进一步探索打哈儿...
此事引发广泛关注!同乡游有辅助... 此事引发广泛关注!同乡游有辅助软件吗,确实存在有辅助app(有挂技巧)-哔哩哔哩1.同乡游有辅助软件...
反观!玉海楼辅助器,好像存在有... 反观!玉海楼辅助器,好像存在有辅助软件(有挂辅助)-哔哩哔哩1.玉海楼辅助器 选牌创建新账号,点击进...
据文件显示!汇友游戏辅助,本来... 据文件显示!汇友游戏辅助,本来真的是有辅助app(有挂细节)-哔哩哔哩据文件显示!汇友游戏辅助,本来...
最终!途游四川小程序脚本辅助,... 最终!途游四川小程序脚本辅助,确实有挂辅助插件(有挂工具)-哔哩哔哩1、下载好途游四川小程序脚本辅助...
近期!wepoker辅助器是真... 近期!wepoker辅助器是真的吗,都是有挂辅助软件(果真有挂)-哔哩哔哩1、wepoker辅助器是...
现有说明如下!广东雀神智能插件... 现有说明如下!广东雀神智能插件免费,一直真的是有辅助脚本(有挂技巧)-哔哩哔哩1、广东雀神智能插件免...
针对!都莱软件安装辅助,好像存... 针对!都莱软件安装辅助,好像存在有辅助软件(有挂辅助)-哔哩哔哩1、进入到都莱软件安装辅助是否有挂之...