通过验证将表单分为多个组件 [英] Dividing a form into multiple components with validation

查看:110
本文介绍了通过验证将表单分为多个组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个具有角2的大窗体.但是我想创建具有多个组件的此窗体,如下面的示例所示.

应用程序组件

I want to create a single big form with angular 2. But I want to create this form with multiple components as the following example shows.

App component

<form novalidate #form1="ngForm" [formGroup]="myForm">
<div>
    <address></address>
</div>
<div>
    <input type="text" ngModel required/>
</div>

<input type="submit" [disabled]="!form1.form.valid" > </form>

地址组件

<div>
<input type="text" ngModel required/> </div>

当我使用上面的代码时,可以根据需要在浏览器中看到它,但是在删除地址组件中的文本时未禁用提交"按钮.
但是,当我删除应用程序组件中输入框中的文本时,该按钮已正确禁用.

When I use the code above it was visible in the browser as i needed but the submit button was not disabled when I delete the text in address component.
But the button was disabled correctly when I delete the text in input box in app component.

推荐答案

我将使用一种反应良好的反应形式,对于您的评论,

I would use a reactive form which works quite nicely, and as to your comment:

这个还有其他简单的例子吗?也许是没有循环的相同示例

我可以举个例子.您需要做的就是嵌套FormGroup并将其传递给孩子.

I can give you an example. All you need to do, is to nest a FormGroup and pass that on to the child.

假设您的表单看起来像这样,并且您想将address表单组传递给子级:

Let's say your form looks like this, and you want to pass address formgroup to child:

ngOnInit() {
  this.myForm = this.fb.group({
    name: [''],
    address: this.fb.group({ // create nested formgroup to pass to child
      street: [''],
      zip: ['']
    })
  })
}

然后在您的父母中,只需传递嵌套的表单组:

Then in your parent, just pass the nested formgroup:

<address [address]="myForm.get('address')"></address>

在您的孩子中,对嵌套表单组使用@Input:

In your child, use @Input for the nested formgroup:

@Input() address: FormGroup;

在您的模板中使用[formGroup]:

<div [formGroup]="address">
  <input formControlName="street">
  <input formControlName="zip">
</div>

如果您不想创建一个实际的嵌套表单组,则不需要这样做,您可以将父表单传递给子表单,这样,如果您的表单看起来像这样:

If you do not want to create an actual nested formgroup, you don't need to do that, you can just then pass the parent form to the child, so if your form looks like:

this.myForm = this.fb.group({
  name: [''],
  street: [''],
  zip: ['']
})

您可以传递所需的任何控件.使用与上述相同的示例,我们只想显示streetzip,子组件保持不变,但是模板中的子标记看起来像:

you can pass whatever controls you want. Using the same example as above, we would only like to show street and zip, the child component stays the same, but the child tag in template would then look like:

<address [address]="myForm"></address>

这里是

演示 ,这是第二个 演示

Demo of first option, here's the second Demo

更多信息> 此处 有关嵌套的模型驱动表单.

More info here about nested model-driven forms.

这篇关于通过验证将表单分为多个组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆