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

相关内容

热门资讯

今日焦点!pokemmo手机版... 今日焦点!pokemmo手机版修改器(辅助挂)果然是真的有挂(有挂技术)今日焦点!pokemmo手机...
程序员教你!德州局透视(辅助挂... 程序员教你!德州局透视(辅助挂)一直存在有挂(果真有挂)所有人都在同一条线上,像星星一样排成一排,每...
热门推荐!pokemmo手机辅... 热门推荐!pokemmo手机辅助软件(辅助挂)确实存在有挂(证实有挂)1、操作简单,无需pokemm...
一分钟教你!hhpoker真的... 一分钟教你!hhpoker真的有透视吗(辅助挂)果然真的有挂(真的有挂)1、金币登录送、破产送、升级...
每日必备!we-poker辅助... 每日必备!we-poker辅助器(辅助挂)切实有挂(确实有挂)1、we-poker辅助器模拟器是什么...
重大发现!wepoker透视挂... 重大发现!wepoker透视挂底牌(辅助挂)一直真的是有挂(确实有挂)wepoker透视挂底牌透视方...
推荐一款!wepoker轻量版... 推荐一款!wepoker轻量版辅助(辅助挂)总是是有挂(真的有挂)1、许多玩家不知道wepoker轻...
一分钟教会你!wpk安卓下载辅... 一分钟教会你!wpk安卓下载辅助(辅助挂)果然真的是有挂(真的有挂)1、实时wpk安卓下载辅助透视辅...
分享开挂内幕!hhpoker有... 分享开挂内幕!hhpoker有没有辅助(辅助挂)总是真的是有挂(有挂方式)1、超多福利:超高返利,海...
揭秘几款!wejoker辅助器... 揭秘几款!wejoker辅助器要钱玩吗(辅助挂)本来真的有挂(有挂技术)wejoker辅助器要钱玩吗...