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

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

问题描述

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

解决方案

准备表格

需要为每个控件添加ngControl

ngControlGroup 到输入和

元素之间的每个元素

让您的表单控件由 NgForm 指令收集和管理.

引用表单

如果您的模板中只有一个表单,您可以使用

@ViewChild(NgForm) formA;

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

并使用

获取参考

@ViewChild('formA') formA;

然后你可以像

一样检查pristine状态

routerCanDeactivate() {返回 this.form.pristine;}

Plunker 示例

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.

解决方案

preparing the form

You need to add ngControl to each control

<input ngControl="someName" ...>

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

<div ngControlGroup="groupName">

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

referencing the form

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">

and get a reference using

@ViewChild('formA') formA;

then you can check pristine status like

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

Plunker example

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

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