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

相关内容

热门资讯

解迷透视!hhpoker德州牛... 解迷透视!hhpoker德州牛仔视频,微乐游戏兑换码大全,要领教程(有挂规律)-哔哩哔哩1、下载好h...
必备透视!wepoker有没有... 必备透视!wepoker有没有挂,微乐小程序黑科技app入口,步骤教程(有挂教学)-哔哩哔哩1、每一...
有挂透视!wepoker怎么开... 有挂透视!wepoker怎么开辅助,微信微乐陕西挖坑小程序下载,窍要教程(有挂秘笈)-哔哩哔哩1、w...
曝光透视!wpk模拟器是什么,... 曝光透视!wpk模拟器是什么,微信小程序微乐破解器,阶段教程(有挂规律)-哔哩哔哩1、上手简单,内置...
解迷透视!wpk透视辅助靠谱吗... 解迷透视!wpk透视辅助靠谱吗,微乐游戏小程序脚本,指南书教程(有挂工具)-哔哩哔哩1、每一步都需要...
解谜透视!哈糖大菠萝有没有挂,... 解谜透视!哈糖大菠萝有没有挂,微乐家乡小程序脚本,方针教程(有挂教学)-哔哩哔哩1、哈糖大菠萝有没有...
分享透视!wepoker私人局... 分享透视!wepoker私人局透视插件,微信小程序游戏破解器,手段教程(真实有挂)-哔哩哔哩1、每一...
解密透视!aapoker ai... 您好,aapoker ai插件这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054...
解密透视!拱趴大菠萝作弊方法,... 解密透视!拱趴大菠萝作弊方法,微信微乐跑得快游戏辅助脚本,方针教程(详细教程)-哔哩哔哩1)拱趴大菠...
了解透视!pokemomo辅助... 了解透视!pokemomo辅助软件,微乐河南家乡麻将辅助脚本,策略教程(有挂猫腻)-哔哩哔哩1、po...