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

相关内容

热门资讯

总算清楚!We poker辅助... 总算清楚!We poker辅助器下载(辅助挂)其实是真的有挂(的确有挂辅助插件)1、进入到是否有挂之...
必看攻略!hh poker插件... 必看攻略!hh poker插件下载(辅助挂)都是真的有挂(有挂方针辅助攻略)1、全新机制【ai辅助工...
信息共享!hhpoker俱乐部... 信息共享!hhpoker俱乐部是干嘛的(辅助挂)一贯存在有挂(有挂方略辅助脚本)1、下载好正确养号方...
一分钟了解!wepoker私人... 一分钟了解!wepoker私人局透视插件(辅助挂)都是存在有挂(新版有挂辅助app)1、上手简单,内...
盘点一款!wepoker私人局... 盘点一款!wepoker私人局透视教程(辅助挂)一直是有挂(存在有挂辅助方法)1、辅助软件下载优化,...
玩家必备科普!竞技联盟透视插件... 玩家必备科普!竞技联盟透视插件(辅助挂)好像真的有挂(有挂教学辅助攻略)1. 选牌创建新账号,点击进...
终于懂了!aapoker怎么拿... 终于懂了!aapoker怎么拿好牌(辅助挂)其实是真的有挂(确实有挂辅助技巧)终于懂了!aapoke...
玩家必看分享!wepoker有... 玩家必看分享!wepoker有脚本吗(辅助挂)本来存在有挂(有挂规律辅助工具)1)有没有挂:进一步探...
9分钟了解!we-poker软... 9分钟了解!we-poker软件(辅助挂)果然有挂(真实有挂辅助方法)1、全新机制【ai辅助工具激活...
推荐十款!wepoker有什么... 推荐十款!wepoker有什么规律(辅助挂)其实有挂(有挂工具辅助脚本)1、打开软件启动之后找到中间...