简体   繁体   English

在Angular 2中验证嵌套表单

[英]Validating nested forms in Angular 2

I have a form which has three components in it. 我有一个包含三个组成部分的表格。 The following is the html of the form: 以下是表单的html:

<div class="p-r-0 m-t-1 p-r-half p-l-half">
    <div class="tab-content">        
        <div *ngIf="vitalsData != null">
            <emp-info *ngIf="far == '1'" [(dataContext)]="empData"></emp-info>
            <emp-work *ngIf="sections == '2'" [(dataContext)]="empData"></faa-ch145>
        </div>
    </div>
    <div class="right pull-top pos-relative">
           <button class="btn btn-primary" type="button">Reset</button>
           <button class="btn btn-primary" type="button">Save</button>
    </div>
</div>

There are two components emp-info and emp-work. emp-info和emp-work有两个部分。 The emp-info and emp-work pages have some required fields. emp-info和emp-work页面具有一些必填字段。 Now when I save the required fields should be validated. 现在,当我保存所需的字段时,应进行验证。 But I have the required fields in the child component and the save button in the parent component. 但是我在子组件中有必填字段,在父组件中有保存按钮。 Could anyone let me know how we could validate and display errors for the fields in the child component. 谁能让我知道我们如何验证和显示子组件中字段的错误。

Angular Forms doesn't validate the Component internals. Angular Forms不会验证Component内部。 If you would like to validate emp-info | 如果您想验证emp-info | emp-work components then they should implement ControlValueAccessor . emp-work组件,则它们应实现ControlValueAccessor Thus Angular will be able to operate with the custom component (it will be fully functional FormControl). 因此,Angular将能够使用自定义组件进行操作(它将是功能齐全的FormControl)。

Another option, which I believe will be more suitable when custom components are just containers, is to pass the FormGroup instance and thus connect internal form controls. 我相信另一种选择是传递自FormGroup实例,从而连接内部表单控件,这在自定义组件只是容器时会更适合。 Check Angular's documentation on this topic: 查看有关此主题的Angular文档:

https://angular.io/docs/ts/latest/cookbook/dynamic-form.html#!#question-form-components https://angular.io/docs/ts/latest/cookbook/dynamic-form.html#!#question-form-components

Notice how the DynamicFormQuestionComponent receives the FormGroup instance. 注意DynamicFormQuestionComponent如何接收FormGroup实例。

emp-work and emp-info are created with FormControl . emp-work和emp-info是使用FormControl创建的。 Then put both inside FormGroup . 然后将两者都放入FormGroup Inside your object factory, you can use Validators.required Or any of it's attributes. 在对象工厂内部,您可以使用Validators.required或其任何属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM