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

相关内容

热门资讯

交流学习经验!哈糖大菠萝助手,... 交流学习经验!哈糖大菠萝助手,hhpoker到底可以作弊吗,竟然存在有挂(竟然有挂)是不是有人用挂微...
一分钟揭秘!aapoker如何... 一分钟揭秘!aapoker如何设置胜率,德普之星透视辅助插件,本来是真的有挂(有挂细节);1、下载好...
近日!aa poker辅助,德... 近日!aa poker辅助,德扑之星私人局辅助免费,本来真的有挂(有挂细节)1、德扑之星私人局辅助免...
一直以来!hhpoker作弊实... 一直以来!hhpoker作弊实战视频,智星德州辅助译码插件靠谱吗,一直确实有挂(有挂总结)运智星德州...
重大发现!wepokerplu... 重大发现!wepokerplus到底是挂了吗,德州透视hhpoker,果然有挂(有挂方略)1、有没有...
据相关数据显示!wepoker... 据相关数据显示!wepoker私人定制透视,智星德州有脚本吗,一贯是真的有挂(有挂实锤)一、智星德州...
科普攻略!wepoker插件程... 科普攻略!wepoker插件程序激活码,hhpoker一直输有挂吗,其实有挂(新版有挂)1、进入到w...
有了最新消息!wepoker怎... 有了最新消息!wepoker怎么增加运气,如何下载德普之星辅助软件,本来确实有挂(有挂辅助)1、进入...
必备辅助推荐!we poker... 必备辅助推荐!we poker插件,wepoker永久免费脚本,原来是真的有挂(有挂分析)辅助器是一...
据统计!wepoker怎么设置... 据统计!wepoker怎么设置透视,德普之星透视辅助插件,本来是真的有挂(有挂透视)1.德普之星透视...