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装饰器传递表单对象,从而实现表单的嵌套。

相关内容

热门资讯

透视策略!wpk辅助插件(WP... 透视策略!wpk辅助插件(WPK透视)原来是有辅助方法(哔哩哔哩)一、wpk辅助插件游戏安装教程牌型...
透视手筋!wpk俱乐部辅助器(... 透视手筋!wpk俱乐部辅助器(WePoKer功能)都是是真的有辅助脚本(哔哩哔哩)1、进入到wpk俱...
透视技法!wepoker有机器... 透视技法!wepoker有机器人吗(WPK俱乐部)本来有辅助攻略(哔哩哔哩)1、不需要AI权限,帮助...
透视模块!wepoker私人局... 透视模块!wepoker私人局透视方法(AApoker安全)其实真的有辅助脚本(哔哩哔哩)一、wep...
透视讲义!wepoker透视最... 透视讲义!wepoker透视最简单三个步骤(WePoKer内购)一直真的有辅助脚本(哔哩哔哩)1、超...
透视经验!hhpoker为什么... 透视经验!hhpoker为什么一直输(WePoKer用挂)总是真的有辅助神器(哔哩哔哩)1、hhpo...
透视资料!拱趴大菠萝万能辅助器... 透视资料!拱趴大菠萝万能辅助器(透视)约局吧能不能开挂(辅助)竟然存在有app(哔哩哔哩)1、玩家可...
透视窍门!pokemmo脚本辅... 透视窍门!pokemmo脚本辅助器下载(透视)epoker底牌透视(辅助)总是一直都是有攻略(哔哩哔...
透视举措!wepoker安装教... 透视举措!wepoker安装教程(WePoKer好牌)真是存在有辅助软件(哔哩哔哩)1、在wepok...
透视教程书!菠萝德普辅助器免费... 透视教程书!菠萝德普辅助器免费版在哪里(透视)来玩app破解版(辅助)本来一直都是有方法(哔哩哔哩)...