表单内的多个子组件

表单内的多个子组件

本文介绍了表单内的多个子组件-Angular 2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理大型表单,因此我计划将表单截断为多个子组件,这有助于简化集成和可维护性.我正在尝试使用表单生成器来实现这一点.

I am working on big form, so i plan to truncate the form into multiple child components which helps for easy integration and maitainbility. Using form builder i am trying to implement this.

mainform.html

    <form novalidate (ngSubmit)="onSubmit(formDetail);" [formGroup]="formDetail">
      <label>
        <span>Name</span>
          <input
          type="text"
          placeholder="Enter emp name"
          formControlName="name">
      </label>
      <app-userinfo></app-userinfo> <!-- Child component 1 -->
      <app-useracc></app-useracc> <!-- Child component 2 -->
    </form>

mainform.ts

export class MainformComponent implements OnInit {
  formDetail: FormGroup;
  constructor(private formBuilder: FormBuilder) { }

  ngOnInit() {
      this.formDetail= this.formBuilder.group({
        name:'',
      userinfo: this.formBuilder.group({
        userid: '',
        userph: ''
      }),
      useracc: this.formBuilder.group({
        useracc: '',
        usertransfer: ''
      })
    });
  }
  onSubmit(value:User){
    debugger;
  }
}

Console.log

formControlName must be used with a parent formGroup directive.  You'll want to add a formGroup

是否可以将表单组件嵌套为单独的子代?

Is it possible to nested form component as a seperate child ?

推荐答案

您需要使用Input()并将该sub- FormGroup传递给子级.我在这里进行了一些更改,并创建了一个名为useraccount而不是useracc的组,以将控件与该组分开:

You need to use Input() and pass that sub-FormGroup to the child. I changed it a bit here and made the group named useraccount instead of useracc to separate the control from the group:

您的父级用户帐户子组:

Your sub group for useraccount in your parent:

  ...
  useraccount: this.formBuilder.group({
    useracc: '',
  })
  ...

因此,父级中相关的子级组件标签应如下所示:

So, the related child component tag in the parent should look something like this:

<app-useracc [useraccount]="formDetail.controls.useraccount"></app-useracc>

然后在您的子组件中添加输入:

And then add input in your child component:

@Input() useraccount: FormGroup;

和模板可能看起来像这样:

and template could look like this:

<div [formGroup]="useraccount">
  <input formControlName="useracc">
</div>

工作中 样本

这篇关于表单内的多个子组件-Angular 2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 03:19