How to get reference to Angular built ControlGroup from within a Component?

纵饮孤独 提交于 2019-12-19 11:55:08

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/36583078/how-to-get-reference-to-angular-built-controlgroup-from-within-a-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!