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 poke... 一分钟快速了解!we poker插件(辅助挂)原来真的有挂(有挂详情辅助器)1)辅助插件:进一步探索...
免费测试版!wepoker怎么... 免费测试版!wepoker怎么增加运气(辅助挂)总是真的有挂(真的有挂辅助技巧)一、游戏安装教程牌型...
信息共享!wepoker辅助器... 信息共享!wepoker辅助器官方(辅助挂)本来有挂(有挂分享辅助方法)1、许多玩家不知道辅助怎么退...
热点讨论!wepokerplu... 热点讨论!wepokerplus外挂(辅助挂)本来真的有挂(有挂规律辅助攻略)一、可以开透视的定义与...
今日公布!wepoker怎么获... 今日公布!wepoker怎么获得好牌(辅助挂)果然真的是有挂(讲解有挂辅助脚本)脚本下载中分为三种模...
科普常识!德普之星有透视辅助吗... 科普常识!德普之星有透视辅助吗(辅助挂)切实真的是有挂(有挂实锤辅助工具)1、游戏颠覆性的策略玩法,...
推荐十款!wepoker有没有... 推荐十款!wepoker有没有透视方法(辅助挂)一贯真的有挂(讲解有挂辅助攻略)进入游戏-大厅左侧-...
技巧知识分享!拱趴大菠萝万能辅... 技巧知识分享!拱趴大菠萝万能辅助器(辅助挂)本来是有挂(有挂规律辅助软件)1、游戏颠覆性的策略玩法,...
9分钟了解!hhpoker必备... 9分钟了解!hhpoker必备开挂(辅助挂)都是真的有挂(竟然有挂辅助技巧)1、用户打开应用后不用登...
玩家攻略推荐!wepoker辅... 玩家攻略推荐!wepoker辅助器最新版本更新内容(辅助挂)本来有挂(有挂教程辅助脚本)是不是有人用...