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

相关内容

热门资讯

辅助透视!pokemmo辅助官... 辅助透视!pokemmo辅助官网!其实一直总是有辅助工具(有挂攻略)-哔哩哔哩1、实时pokemmo...
详细透视!约局吧怎么看有没有挂... 详细透视!约局吧怎么看有没有挂!确实是真的有辅助软件(有挂秘籍)-哔哩哔哩1、游戏颠覆性的策略玩法,...
揭幕透视!红龙poker辅助平... 揭幕透视!红龙poker辅助平台!都是真的有辅助神器(讲解有挂)-哔哩哔哩进入游戏-大厅左侧-新手福...
关于透视!xpoker辅助助手... 关于透视!xpoker辅助助手!真是有辅助脚本(真的有挂)-哔哩哔哩1、超多福利:超高返利,海量正版...
科普透视!uupoker有透视... 科普透视!uupoker有透视吗!竟然一直都是有辅助插件(真是有挂)-哔哩哔哩1、完成uupoker...
解迷透视!cloudpoker... 解迷透视!cloudpoker怎么开挂!原来一直都是有辅助技巧(存在有挂)-哔哩哔哩1、解迷透视!c...
专业透视!德州透视插件!切实有... 专业透视!德州透视插件!切实有辅助软件(真的有挂)-哔哩哔哩1、进入到德州透视插件是否有挂之后,能看...
辅助透视!sohoo竞技联盟辅... 辅助透视!sohoo竞技联盟辅助器!好像是有辅助教程(真的有挂)-哔哩哔哩1)sohoo竞技联盟辅助...
了解透视!pokemmo辅助官... 了解透视!pokemmo辅助官网!好像是真的有辅助插件(有挂详细)-哔哩哔哩1、pokemmo辅助官...
解密透视!聚星ai辅助工具下载... 解密透视!聚星ai辅助工具下载!其实是有辅助神器(的确有挂)-哔哩哔哩1、让任何用户在无需聚星ai辅...