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

相关内容

热门资讯

一秒答解(WPK原理)外挂透明... 一秒答解(WPK原理)外挂透明挂辅助挂(黑科技)软件透明挂(真是有挂)-哔哩哔哩;WPK原理是一项W...
实测教程(智星德州菠萝安全)外... 实测教程(智星德州菠萝安全)外挂透明挂辅助器(黑科技)德扑之星(证实有挂)-哔哩哔哩;智星德州菠萝安...
盘点十款(WPK辨别)外挂透明... 盘点十款(WPK辨别)外挂透明挂辅助工具(黑科技)透视辅助(有挂攻略)-哔哩哔哩是一款可以让一直输的...
重要通知(新版Wepoke)外... 重要通知(新版Wepoke)外挂透明挂辅助器(黑科技)插件(有挂总结)-哔哩哔哩;是一款可以让一直输...
分享一款(微扑克智能ai)外挂... 分享一款(微扑克智能ai)外挂透明挂辅助插件(黑科技)保险规则(有挂工具)-哔哩哔哩;大家肯定在之前...
玩家必看攻略(德州实战)外挂透... 玩家必看攻略(德州实战)外挂透明挂辅助安装(黑科技)德州扑克系统规律(有挂教程)-哔哩哔哩是一款可以...
一秒答解(WePoKe辅助插件... 您好:WePoKe辅助插件这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户...
总算了解(WPK透明)外挂透明... 总算了解(WPK透明)外挂透明挂辅助黑科技(黑科技)有正规(确实有挂)-哔哩哔哩;AI辅助机器人普及...
教程辅助(德州ai代理)外挂透... 教程辅助(德州ai代理)外挂透明挂辅助下载(黑科技)辅助技巧(有挂秘笈)-哔哩哔哩;AI辅助机器人普...
推荐攻略(德州手机)外挂透明挂... 推荐攻略(德州手机)外挂透明挂辅助下载(黑科技)ai机器人(了解有挂)-哔哩哔哩;超受欢迎的德州手机...