[英]How can I access or check validation of the child component's template driven form in the super parent's component
Say i am having a set of components with the parent-child relationship. 说我有一组具有父子关系的组件。 The the structure is as follows: [A]-->[B]-->[C]-->[D] (ie) A is the parent of B , B is the parent of C , C is the parent of D. I need to check the validity of template-driven form in component D from the component A .
结构如下: [A]-> [B]-> [C]-> [D] (即)A是B的父级,B是C的父级,C是B的父级D.我需要从A组件检查D组件中模板驱动表单的有效性。 I have tried using @viewchild().
我尝试使用@viewchild()。 in my componentA.html
在我的componentA.html中
<form #mainform ="ngform"> <button [disabled]= "componentB?.ComponentC?.ComponentD?.form?.invalid"> </button> </form>
This approach is not working. 这种方法行不通。
How can I achieve this from A to D without using event emitter? 如何在不使用事件发射器的情况下实现从A到D的目标?
It does not matter how deeply it is nested in the component tree. 嵌套在组件树中的深度无关紧要。 It matters how it is nested in the form tree.
它如何嵌套在表单树中很重要。
Asumming the child controls are named child
, grandchild
and grandgrandchild
you can do something like this: Asumming子控件被命名为
child
, grandchild
和grandgrandchild
你可以做这样的事情:
<form #mainform="ngform">
<button [disabled]="mainform.control.get('child.grandchild.grandgrandchild').invalid">
</button>
</form>
We use the mainform.control
to get the access to the underlying FormGroup
. 我们使用
mainform.control
获取对基础FormGroup
的访问。 Now we have an access to all methods on the FormGroup
class. 现在,我们可以访问
FormGroup
类上的所有方法。 You can see the full list here . 您可以在此处查看完整列表。
Next we use the get
method to traverse the form tree and reach for the child control. 接下来,我们使用
get
方法遍历表单树并到达子控件。
If you have a form tree like this: 如果您有这样的表单树:
mainform: {
child: {
grandchild: {
grandChild
}
}
}
Where mainform
, child
, and grandchild
are FromGroups
and grandgrandchild is a
FormControl`. 其中
mainform
, child
和grandchild
是FromGroups
, grandgrandchild is a
FormControl`。
You can access the grandgrandchild
by typing: mainForm.get('child.grandchild.grandchild')
您可以通过键入以下
mainForm.get('child.grandchild.grandchild')
来访问grandgrandchild
: mainForm.get('child.grandchild.grandchild')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.