跨多个组件的表单验证

时间:2016-09-21 13:09:55

标签: angular angular2-template

我正在使用Angular2。我在我的主要组件中有这个:

<form #f="ngForm" novalidate (ngSubmit)="save()">
  <child [cosField]="cosField" [f]="f"></child>
  <button type="submit" [disabled]="!f.valid">Submit</button>
</form>

我从这个组件调用了一个不同的子组件。 子组件中的代码是:

<input type="text" name="flow" [(ngModel)]="cosField.value" required  #name="ngModel"/>
<div [hidden]="name.valid || (!f.submitted)" 
    class="error">
  An error has occurred.
</div>

我想在子组件中访问此局部变量f。基本上用于表单验证。如果子组件中的某些验证失败,则消息&#34;发生错误&#34;得到正确显示。但是在主组件中,f.valid仍然为true,因此始终启用提交按钮。但是,如果我将子组件内联到主组件本身,那么一切正常,如果验证失败,则禁用“提交”按钮。 有没有办法将表单拆分为多个组件,并且仍然能够使用局部变量f有效地验证控件?

1 个答案:

答案 0 :(得分:0)

使用Angular2 @Output EventEmitter将值传递出子组件,这样父组件就可以捕获事件并更新f的有效性。

您必须为父组件和子组件添加组件逻辑。 Typescript中的模式看起来像这样:

父组件:

...<imports>...
@Component({
    selector: 'parent-component',
    ...
})
export class ParentComponent implements OnInit {
    ...
    ngOnInit() {
        ...
    });

    childChanged(event) {
        // Use event value to do validity checking here.
    }
}

子组件:

import { Component, Output, EventEmitter } from '@angular/core';
<...other imports...>

@Component({
    selector: 'child',
    ...
})
export class ChildComponent implements OnInit {
    @Output() change: EventEmitter<any> = new EventEmitter();

    ...
}

现在,您的孩子的input可以在传播给父母的@Output上发出一个事件。例如,孩子可以传播模糊变化并传递name的有效性:

<input type="text" name="flow" [(ngModel)]="cosField.value" required  #name="ngModel" (blur)="change.emit(name.valid)" />

家长通过查找您的自定义change活动来获取更改并处理有效性状态:

<child [cosField]="cosField" [f]="f" (change)="childChanged($event)"></child>

以下是我在第一次了解这些内容时发现的其他参考资料: