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透视有用吗(起初真的有挂);暗...
玩家必备攻略!科乐游戏辅助脚本... 玩家必备攻略!科乐游戏辅助脚本视频(辅助挂)竞技联盟破解版最新版(本来真的是有挂)是一款可以让一直输...
详细说明!乐达app辅助(辅助... 详细说明!乐达app辅助(辅助挂)aapoker免费透视脚本(往昔有挂);小薇(透视辅助)致您一封信...
记者发布!jj斗地主外开挂(辅... 记者发布!jj斗地主外开挂(辅助挂)德普之星透视辅助软件激活码(从前存在有挂);1、很好的jj斗地主...
一分钟了解!广东雀神祈福真的有... 一分钟了解!广东雀神祈福真的有用吗(辅助挂)wepoker好友房开挂(先前真的有挂);1、超多福利:...
重大来袭!吉安中至小程序(辅助... 重大来袭!吉安中至小程序(辅助挂)wepoker永久免费脚本(确实真的有挂);人气非常高,ai更新快...
我来向大家传授!微信小程序多功... 您好:微信小程序多功能辅助这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户...
大家学习交流!途游大作战辅助(... 您好:途游大作战辅助这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户的牌特...
攻略讲解!花舍辅助(辅助挂)w... 您好,花舍辅助这款游戏可以开挂的,确实是有挂的,需要了解加微【136704302】很多玩家在这款游戏...