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获得嵌套表单的值。

相关内容

热门资讯

外挂步骤!智星菠萝德州辅助译码... 外挂步骤!智星菠萝德州辅助译码插件靠谱吗,哈糖大菠萝软件下载-切实真的是有辅助app(哔哩哔哩)1)...
外挂课程!佛手大菠萝辅助,红龙... 外挂课程!佛手大菠萝辅助,红龙poker辅助工具-总是是真的有辅助教程(哔哩哔哩)1、红龙poker...
外挂项目!aa poker辅助... 外挂项目!aa poker辅助包,uupoker透视-果然真的是有辅助app(哔哩哔哩)1、超多福利...
外挂指南书!hardrock透... 外挂指南书!hardrock透视工具,德州透视是真的吗-确实是有辅助攻略(哔哩哔哩)该软件可以轻松地...
外挂烘培!线上德州的辅助器是什... 外挂烘培!线上德州的辅助器是什么,poker master辅助-确实真的是有辅助脚本(哔哩哔哩)1、...
外挂方案!德普之星透视辅助软件... 外挂方案!德普之星透视辅助软件是真的吗,pokernow辅助工具-原来真的有辅助脚本(哔哩哔哩)po...
外挂诀窍!大菠萝免费辅助器,来... 外挂诀窍!大菠萝免费辅助器,来玩app 德州 辅助-竟然有辅助脚本(哔哩哔哩)大菠萝免费辅助器脚本下...
外挂手册!智星德州有脚本吗,佛... 外挂手册!智星德州有脚本吗,佛手在线是不是有挂-一直一直都是有辅助方法(哔哩哔哩)1、进入游戏-大厅...
外挂法门!德普之星透视辅助软件... 外挂法门!德普之星透视辅助软件下载,德州透视是真的吗-其实是真的有辅助神器(哔哩哔哩)1、该软件可以...
外挂攻略!wepoker透视有... 外挂攻略!wepoker透视有吗,智星德州有脚本吗-竟然一直总是有辅助插件(哔哩哔哩)1、下载好智星...