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、每一步都需要思考,不同水平的挑战会更...
热点推荐!aapoker辅助挂... 热点推荐!aapoker辅助挂多功能透视工具,一直真的是有挂(有挂教程)在进入aapoker软件靠谱...
详细说明!AAPoKer辅助挂... 详细说明!AAPoKer辅助挂多功能透视工具,切实有挂(有挂神器)AAPoKer脚本下载中分为三种模...
推荐攻略!AAPoKer辅助挂... 推荐攻略!AAPoKer辅助挂多功能透视工具,确实存在有挂(有挂方法);1、下载好AAPoKer脚本...
专业讨论!WPK辅助挂多功能透... 专业讨论!WPK辅助挂多功能透视工具,总是存在有挂(有人有挂)1.WPK 选牌创建新账号,点击进入游...
推荐一款!智星德州扑克辅助挂多... 推荐一款!智星德州扑克辅助挂多功能透视工具,一直是真的有挂(今日头条)1、每一步都需要思考,不同水平...
带你了解!智星德州扑克辅助挂多... 您好,智星德州扑克这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多玩家在...
我来教教大家!红龙poker辅... 我来教教大家!红龙poker辅助挂多功能透视工具,都是真的有挂(有挂实锤)1)红龙poker辅助插件...
程序员教你!wepoker辅助... 程序员教你!wepoker辅助挂多功能透视工具,果然存在有挂(有挂攻略)1、玩家可以在wepoker...
一分钟揭秘!德扑圈辅助挂多功能... 一分钟揭秘!德扑圈辅助挂多功能透视工具,确实真的是有挂(有挂详细)1、起透看视 德扑圈辅助软件价格2...