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、德普之星透视软件免费入口官...
透视软件!wepoker新号好... 透视软件!wepoker新号好一点吗,wepoker私人辅助器(透视)一贯真的是有挂;1)wepok...
透视存在!德普之星透视辅助软件... 透视存在!德普之星透视辅助软件(透视)私人局辅助免费(竟然是有挂)1、每一步都需要思考,不同水平的挑...
透视新版!德普之星有辅助软件吗... 透视新版!德普之星有辅助软件吗(透视)透视挂(总是真的有挂)1、德普之星有辅助软件吗ai辅助优化,德...
透视透视!购买wepoker模... 透视透视!购买wepoker模拟器,wepoker能不能透视(透视)原来存在有挂购买wepoker模...
透视透视!wepoker数据分... 透视透视!wepoker数据分析,wepoker插件下载(透视)一直是有挂1、很好的工具软件,可以解...
透视代打!德普之星辅助工具如何... 透视代打!德普之星辅助工具如何设置(透视)app安卓版破解版(一贯存在有挂)1、起透看视 德普之星辅...
透视线上!wepoker作弊方... 透视线上!wepoker作弊方法,wepoker透视方法(透视)一直是真的有挂一、wepoker作弊...
透视苹果版!德普之星app安卓... 透视苹果版!德普之星app安卓版破解版(透视)私人局透视(确实存在有挂);德普之星app安卓版破解版...