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

相关内容

热门资讯

三分钟了解!微乐小程序自建房辅... 三分钟了解!微乐小程序自建房辅助工具插件,微乐小程序免费黑科技(开挂自建房)脚本1、每一步都需要思考...
玩家攻略!微信卡五星辅助器,微... 玩家攻略!微信卡五星辅助器,微乐自建房脚本免费入口(开挂自建房)攻略1、打开软件启动之后找到中间准星...
教程辅助!微乐微信自建房辅助工... 教程辅助!微乐微信自建房辅助工具插件,微乐小程序免费黑科技(开挂自建房)工具所有人都在同一条线上,像...
科技新动态!微信雀神麻将挂件开... 科技新动态!微信雀神麻将挂件开挂辅助,微乐小程序免费黑科技(开挂自建房)方法1、在微信雀神麻将挂件开...
教学盘点!微乐自建房辅助工具挂... 教学盘点!微乐自建房辅助工具挂,微乐家乡麻将自建房辅助app(开挂自建房)方法1、微乐家乡麻将自建房...
终于懂了!微乐小程序麻将自建房... 终于懂了!微乐小程序麻将自建房辅助工具插件,微乐家乡麻将自建房辅助app(开挂自建房)教程1、微乐小...
推荐攻略!微乐自建房辅助工具脚... 推荐攻略!微乐自建房辅助工具脚本,微乐自建房脚本免费入口(开挂自建房)教程推荐攻略!微乐自建房辅助工...
揭秘一下!微乐小程序自建房辅助... 揭秘一下!微乐小程序自建房辅助工具插件,微乐家乡麻将自建房辅助app(开挂自建房)攻略1、微乐小程序...
一分钟了解!微乐小程序麻将自建... 一分钟了解!微乐小程序麻将自建房辅助工具插件,微乐自建房脚本免费入口(开挂自建房)攻略1)微乐小程序...
玩家必备科技!微乐自建房辅助工... 玩家必备科技!微乐自建房辅助工具挂,微乐小程序免费黑科技(开挂自建房)技巧1、打开软件启动之后找到中...