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

相关内容

热门资讯

于此同时!wepoker底牌透... 于此同时!wepoker底牌透视(透视)好像有辅助安装(有挂神器)-哔哩哔哩1、wepoker底牌透...
透视挂!wepoker到底有没... 您好,wepoker到底有没有透视这款游戏可以开挂的,确实是有挂的,需要了解加去威信【1367043...
透视真的!佛手大菠萝辅助(透视... 透视真的!佛手大菠萝辅助(透视)真是真的是有辅助app(有挂神器)-哔哩哔哩1、佛手大菠萝辅助破解器...
针对!菠萝辅助器免费版的功能介... 针对!菠萝辅助器免费版的功能介绍(透视)原来存在有辅助安装(真的有挂)-哔哩哔哩1、针对!菠萝辅助器...
透视智能ai!wepoker私... 透视智能ai!wepoker私局代打(透视)真是存在有辅助辅助器(有挂助手)-哔哩哔哩wepoker...
透视真的!wpk真吗(透视)都... 透视真的!wpk真吗(透视)都是真的有辅助辅助器(揭秘有挂)-哔哩哔哩1、wpk真吗透视辅助软件激活...
透视工具!wepoker私人局... 透视工具!wepoker私人局辅助(透视)一直真的是有辅助安装(有挂方针)-哔哩哔哩1、实时wepo...
现有关情况通报如下!哈糖大菠萝... 现有关情况通报如下!哈糖大菠萝软件下载(透视)原来是有辅助app(有挂分析)-哔哩哔哩所有人都在同一...
近日!wepoker游戏的安装... 近日!wepoker游戏的安装教程(透视)真是真的是有辅助神器(有挂功能)-哔哩哔哩1、wepoke...
透视有挂!we-poker靠谱... 透视有挂!we-poker靠谱吗(透视)竟然真的有辅助软件(存在有挂)-哔哩哔哩we-poker靠谱...