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-p... 备受关注的"we-poker靠谱吗"pokemmo脚本最新版(果然真的是有辅助软件)-哔哩哔哩1、p...
据报道"aapoke... 据报道"aapoker辅助器是真的吗"HH平台挂(好像真的有辅助辅助器)-哔哩哔哩1、下载好aapo...
透视脚本"wepok... 透视脚本"wepoker私人局透视教程"hhpoker辅助挂(都是存在有辅助下载)-哔哩哔哩1、we...
目前来看"pokem... 目前来看"pokemmo辅助器手机版下载"wepoker有辅助器吗(确实是有辅助软件)-哔哩哔哩1、...
这一问题亟待解决"h... 这一问题亟待解决"hh poker软件"wejoker内置辅助(确实真的有辅助插件)-哔哩哔哩1、每...
一直以来"hhpok... 一直以来"hhpoker德州有挂吗"werplan外开挂(切实是有辅助平台)-哔哩哔哩1、操作简单,...
据监测"大菠萝789... 据监测"大菠萝789辅助器下载"hhpoker有透视功能吗(切实是真的辅助平台)-哔哩哔哩1、大菠萝...
截至目前"wepok... 截至目前"wepoker软件安装包"wpk透视辅助下载(好像真的有辅助修改器)-哔哩哔哩wepoke...
备受关注的"hhpo... 备受关注的"hhpoker免费透视脚本"德扑圈透视(原来是有辅助插件)-哔哩哔哩1、hhpoker免...
透视插件"wepok... 透视插件"wepoker免费脚本咨询"wepoker代打辅助(真是是有辅助软件)-哔哩哔哩1、wep...