Angular 2验证以及子组件 [英] Angular 2 validation together with the child component

查看:95
本文介绍了Angular 2验证以及子组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在父组件中,我有一个子组件.两者都有其必填字段.最后,仅当两个组件均有效时(在这种情况下,必须填写所有必填字段),我才需要启用提交按钮.

Inside the parent component I have a child component. Both have their required fields. At the end I need the enable the submit button only if both components are valid (all their required fields are filled in this case).

我该如何做到这一点,尤其是在模板驱动的验证中?

How can I accomplish this, especially with template-driven validation?

种子代码

父级组件

@Component({
    selector: 'parent-comp',
    templateUrl: 'parent.html'
})
export class Parent {

}

<input pInputText name="txt1" id="txt1"
                       required/>

<child-comp></child-comp>

<button pButton type="button" label="Submit"
            [disabled]="IF ONE OF THE COMPS IS NOT VALID"></button>

子组件

@Component({
    selector: 'child-comp',
    templateUrl: 'child.html'
})
export class Child {

}

<input pInputText name="txt2" id="txt2"
                       required/>

推荐答案

要同时验证父级和子级组件,需要将一个表单分为多个组件.

父HTML

For validating both parent and child component, a single form need to be divided into multiple component.

Parent html

<form #parentForm="ngForm">
            <input pInputText name="txt1" id="txt1"
                   required/>

      <child-comp></child-comp>

        <button pButton type="button" label="Submit"
        [disabled]="!parentForm.valid"></button>
        </form>

父组件

 import { Component } from '@angular/core';
 @Component({
       selector: 'parent-comp',
        templateUrl: 'parent.html'
})
export class Parent {

}

子表单不能带有表单标签

<input pInputText name="txt2" id="txt2"
                   required/>

子组件

import { Component } from '@angular/core';
import { ControlContainer, NgForm } from '@angular/forms';
@Component({
selector: 'child-comp',
templateUrl: 'child.html',
viewProviders: [{ provide: ControlContainer, useExisting: NgForm }]
 })
 export class Child {
 }

这篇关于Angular 2验证以及子组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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