如何从组件内部获取对Angular构建的ControlGroup的引用? [英] How to get reference to Angular built ControlGroup from within a Component?

查看:88
本文介绍了如何从组件内部获取对Angular构建的ControlGroup的引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个组件,其中包含模板驱动"表单.我真正想做的是在routerCanDeactivate方法中添加代码以检查表单是否为pristine,如果不是,则在继续导航之前向用户发出警告.我知道Angular采用了模板驱动"形式并构建了一个ControlGroup.在模板中,我可以像这样:<form #hf="ngForm" ...>是否有从组件内部引用它的方法? 如果这不可能,是否有另一种方法可以通过routeCanDeactivate检查表单是否脏了? 谢谢您的帮助.

I have a Component, containing a Template Driven form. What I really want to do is to add a code to routerCanDeactivate method to check if the form is pristine and if not, to warn the user before continuing with navigation. I know that Angular takes a Template Driven form and builds a ControlGroup. In the template, I can get to it like so: <form #hf="ngForm" ...> Is there a way to reference it from within a component? If this is not possible, is there another way to check if the form is dirty from routeCanDeactivate? Thank you for the help.

推荐答案

准备表格

您需要将ngControl添加到每个控件

You need to add ngControl to each control

<input ngControl="someName" ...>

输入和<form>元素之间的每个元素

ngControlGroup

and ngControlGroup to each element between the inputs and the <form> element

<div ngControlGroup="groupName">

通过NgForm指令收集和管理表单控件.

to get your form controls collected and managed by the NgForm directive.

引用表格

如果模板中只有一种形式,则可以使用

If you only have one form in your template you can use

@ViewChild(NgForm) formA;

获取对表单的引用,否则将模板变量添加到表单

to get a reference to the form, otherwise add template variables to the forms

<form ngForm #formA="ngForm">

并使用

@ViewChild('formA') formA;

然后您可以检查pristine状态,例如

then you can check pristine status like

routerCanDeactivate() {
  return this.form.pristine;
}

柱塞示例

这篇关于如何从组件内部获取对Angular构建的ControlGroup的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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