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

相关内容

热门资讯

第2分钟项目!人人燕赵挂,潮汕... 第2分钟项目!人人燕赵挂,潮汕掌手娱辅助器,软件教程(有挂方式)-哔哩哔哩1)潮汕掌手娱辅助器辅助挂...
第9分钟攻略!新道游开挂辅助透... 第9分钟攻略!新道游开挂辅助透视,阿拉游戏中心辅助,透明挂教程(揭秘有挂)-哔哩哔哩1、新道游开挂辅...
8分钟讲义!中至赣牌圈科技,兴... 8分钟讲义!中至赣牌圈科技,兴动互娱脚本,必胜教程(证实有挂)-哔哩哔哩1、打开软件启动之后找到中间...
一分钟要领!福建兄弟水挂,川友... 一分钟要领!福建兄弟水挂,川友汇辅助软件,总结教程(有挂实锤)-哔哩哔哩1、这是跨平台的川友汇辅助软...
7分钟项目!九九山城插件程序,... 7分钟项目!九九山城插件程序,拱趴游戏诀窍,科技教程(有挂分享)-哔哩哔哩1、九九山城插件程序透视辅...
6分钟学习!雀友会广东潮汕辅助... 6分钟学习!雀友会广东潮汕辅助,hhpoker免费辅助器,攻略教程(有挂方式)-哔哩哔哩运雀友会广东...
四分钟绝活儿!新道游正版辅助,... 四分钟绝活儿!新道游正版辅助,卡农辅助,2025版教程(有挂教程)-哔哩哔哩该软件可以轻松地帮助玩家...
2分钟诀窍!微友辅助器免费版v... 2分钟诀窍!微友辅助器免费版v3.0,川友汇挂牌,透牌教程(有挂教学)-哔哩哔哩1、微友辅助器免费版...
3分钟讲义!甘肃白银麻将辅助软... 3分钟讲义!甘肃白银麻将辅助软件,微信边锋辅助软件,靠谱教程(的确有挂)-哔哩哔哩1、玩家可以在甘肃...
三分钟诀窍!福建兄弟十三水辅助... 三分钟诀窍!福建兄弟十三水辅助器下载,欢乐茶馆辅助,揭秘教程(存在有挂)-哔哩哔哩一、福建兄弟十三水...