Angular嵌套表单 父/子组件
创始人
2024-10-29 02:30:33
0

在Angular中,可以使用父子组件的方式来实现嵌套表单。下面是一个示例代码,演示了如何使用父子组件来创建嵌套表单。

首先,创建一个父组件,命名为ParentComponent。在该组件的模板中,使用formGroup指令创建一个表单,并在表单中使用formControlName指令来绑定表单控件。同时,将子组件ChildComponent作为一个子元素添加到父组件的模板中,并将父组件的表单传递给子组件。

parent.component.html:

在父组件的代码中,需要创建一个FormGroup对象来表示父组件的表单,并初始化表单控件。

parent.component.ts:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {
  parentForm: FormGroup;

  constructor(private fb: FormBuilder) { }

  ngOnInit() {
    this.parentForm = this.fb.group({
      name: '',
      email: ''
    });
  }
}

接下来,创建一个子组件ChildComponent。在子组件的模板中,也使用formGroup指令创建一个表单,并在表单中使用formControlName指令来绑定表单控件。

child.component.html:

在子组件的代码中,需要接收父组件传递过来的表单,并创建一个FormGroup对象来表示子组件的表单,并初始化表单控件。

child.component.ts:

import { Component, Input, OnInit } from '@angular/core';
import { FormGroup } from '@angular/forms';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
  @Input() formGroup: FormGroup;
  childForm: FormGroup;

  constructor() { }

  ngOnInit() {
    this.childForm = this.formGroup.group({
      age: '',
      address: ''
    });
  }
}

最后,在模块中引入父组件和子组件,并将它们添加到declarationsexports数组中。

app.module.ts:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { ParentComponent } from './parent.component';
import { ChildComponent } from './child.component';

@NgModule({
  declarations: [
    AppComponent,
    ParentComponent,
    ChildComponent
  ],
  imports: [
    BrowserModule,
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

这样,就完成了一个简单的Angular嵌套表单的父子组件实现。在父组件中创建了一个包含子组件的表单,并在子组件中创建了另一个表单。父子组件之间可以通过@Input装饰器传递表单对象,从而实现表单的嵌套。

相关内容

热门资讯

指导大家!hhpoker可以控... 指导大家!hhpoker可以控制牌吗(辅助挂)好像是真的有挂(确实有挂辅助方法)1)有没有挂:进一步...
发现一款!wepoker有辅助... 发现一款!wepoker有辅助插件吗(辅助挂)原来存在有挂(有挂秘笈辅助插件)1、这是跨平台的轻量版...
玩家必看科普!佛手大菠萝有挂吗... 玩家必看科普!佛手大菠萝有挂吗(辅助挂)果然存在有挂(有挂神器辅助器)1、很好的工具软件,可以解锁游...
重大推荐!wpk透视插件(辅助... 重大推荐!wpk透视插件(辅助挂)竟然是有挂(有挂教程辅助方法)1、首先打开辅助器下载最新版本,在辅...
一分钟教你!hhpoker是内... 一分钟教你!hhpoker是内部控制吗(辅助挂)原来是有挂(有人有挂辅助工具)1、这是跨平台的轻量版...
免费测试版!hhpoker作弊... 免费测试版!hhpoker作弊实战视频(辅助挂)真是是有挂(有挂分析辅助软件)1)免费钻石:进一步探...
信息共享!hhpoker辅助软... 信息共享!hhpoker辅助软件(辅助挂)其实有挂(有挂规律辅助攻略)1、该软件可以轻松地帮助玩家将...
最新通报!hhpoker是正品... 最新通报!hhpoker是正品吗(辅助挂)竟然有挂(竟然有挂辅助器)1、透视辅助软件激活码多个强度级...
科技通报!黑侠破解wepoke... 科技通报!黑侠破解wepoker(辅助挂)确实有挂(有挂存在辅助器)1、完成有辅助插件,帮助玩家取得...
科普分享!wepoker买钻石... 科普分享!wepoker买钻石有用吗(辅助挂)其实真的有挂(有挂技巧辅助脚本)1、不需要AI权限,帮...