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、很好的工具软...
第9分钟辅助挂!微乐云南小程序... 您好,微乐云南小程序辅助器这款游戏可以开挂的,确实是有挂的,需要了解加微【136704302】很多玩...
一分钟辅助挂!如何判断广东雀神... 一分钟辅助挂!如何判断广东雀神挂件的质量(透视)柚子联盟辅助器下载(详细透视外开挂教程)1、每一步都...
五分钟辅助挂!欢乐茶馆挂有没有... 五分钟辅助挂!欢乐茶馆挂有没有(透视)欢乐茶馆辅助(详细透视外开挂教程)1、欢乐茶馆挂有没有系统规律...
八分钟辅助挂!九江讨赏辅助中至... 八分钟辅助挂!九江讨赏辅助中至小程序(透视)捉住捣蛋鸡作弊(详细透视外开挂教程)1、玩家可以在九江讨...
四分钟辅助挂!拱趴大菠萝作弊方... 四分钟辅助挂!拱趴大菠萝作弊方法(透视)三哥玩摆头辅助(详细透视外开挂教程)拱趴大菠萝作弊方法辅助器...
第一分钟辅助挂!拱趴大菠萝如何... 自定义拱趴大菠萝如何会赢系统规律,只需要输入自己想要的开挂功能,一键便可以生成出微扑克专用辅助器,不...
九分钟辅助挂!四川点点长牌系统... 九分钟辅助挂!四川点点长牌系统(透视)钱塘十水三插件(详细透视外开挂教程)1、打开德州poker外挂...
第6分钟辅助挂!微信小程序加速... 自定义微信微乐小程序修改器系统规律,只需要输入自己想要的开挂功能,一键便可以生成出微扑克专用辅助器,...