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链接烘培!wepoker... WPK链接烘培!wepoker私人局俱乐部怎么进,德州微扑克切实是有辅助方法1)wepoker私人局...
WPK安装绝活儿!wepoke... WPK安装绝活儿!wepoker免费脚本咨询,德州微扑克其实真的是有开挂技巧1、wepoker免费脚...
WPK多开技法!德朴之星脚本,... WPK多开技法!德朴之星脚本,德州微扑克一贯存在有辅助教程1、这是跨平台的德朴之星脚本轻量版有透视,...
WPK有透视手册!wepoke... WPK有透视手册!wepoker透视脚本网页,德州微扑克本来真的是有开挂app1、超多福利:超高返利...
WPK私人局演示!wepoke... WPK私人局演示!wepoker辅助透视软件,德州微扑克总是真的有辅助appwepoker辅助透视软...
WPK靠谱策略!wepoker... WPK靠谱策略!wepokerplus开挂,德州微扑克真是真的有开挂教程1、在wepokerplus...
WPK透视版要领!wepoke... WPK透视版要领!wepoker新号好一点吗,德州微扑克切实存在有透视教程wepoker新号好一点吗...
WPK控制牌策略!wepoke... WPK控制牌策略!wepoker透视脚本免费下载,德州微扑克本来存在有辅助攻略wepoker透视脚本...
WPK插件演示!wepoker... WPK插件演示!wepoker网页版透视方法,德州微扑克好像真的有开挂神器1)wepoker网页版透...
WPK作弊窍要!wejoker... WPK作弊窍要!wejoker辅助脚本,德州微扑克好像存在有透视appwejoker辅助脚本辅助器是...