我有一个场景,我在父窗体#parentform中访问两个不同的NgForms,在子组件#childForm&#childForm1中访问其他NgForms,我想检查子窗体的控件的有效性是否在父组件形式中有效 . 如何在angular4中执行此操作 .
我也关注了这个链接:Check if a form is valid from a parent component using Angular 4
每次我得到未定义的子组件形式的参考 .
我的代码是这样的 .
parent.component.html
<form class="form-wrapper" (ngSubmit)="parentForm.form.valid && save()" #parentForm="ngForm" novalidate>
<input id="firstName" type="text" placeholder="" class="validate" name="firstName" [(ngModel)]="firstname_" #firstName="ngModel" required>
</form>
<child-component></child-component>
child.component.html
<form class="form-wrapper" (ngSubmit)="childForm.form.valid && save()" #childForm="ngForm" novalidate>
<input id="phoneNumber" type="text" placeholder="" class="validate" name="phoneNumber" [(ngModel)]="phone_" #phoneNumber="ngModel" required>
</form>
<form class="form-wrapper" (ngSubmit)="childForm1.form.valid && save()" #childForm1="ngForm" novalidate>
<input id="mobileNumber" type="text" placeholder="" class="validate" name="mobileNumber" [(ngModel)]="mobile_" #mobileNumber="ngModel" required>
</form>
现在我想验证子组件形式“childForm”和“childForm1”是否有效,以父表格形式 .
同样在https://stackblitz.com/edit/angular-cjorjz转载......
1 回答
所以你想要的是将
parentForm.form.status
传递给带有 @Input() 的孩子 .在父html中:
然后在你的孩子:
并检查它
console.log(this.boolean)
它或将{{boolean}}
放在html中 . 或childForm.form.valid && save() && boolean
在html中 .EDIT
要发回验证:
在子组件中,您必须触发@Output(),因此在html上使用change事件:
在html中你所有的孩子表格:
在你的父html中:
在父组件中: