Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get ngForm variable reference in the component class?

Given the following...

.html

<form (ngSubmit) = "onSubmit()"
          #heroForm = "ngForm">
      {{diagnostic}}
      <div class = "form-group">
        <label for = "name">Name</label>
        <input type = "text"
               class = "form-control"
               required
               [(ngModel)] = "model.name"
               ngControl = "name"
               #name = "ngForm"
               #spy>
        <p *ngIf = "name.dirty"
           class = "alert alert-danger">
          Name is required
        </p>
        <!--<p [hidden] = "name.dirty"-->
           <!--class = "alert alert-danger">-->
          <!--Name is required-->
        <!--</p>-->
      </div>

..

..is it possible to get the #name = "ngForm" (ngForm) reference in the .dart component to allow manipulation? Any suggestion and correction is welcome.

like image 722
st_clair_clarke Avatar asked Jan 15 '16 22:01

st_clair_clarke


People also ask

How do I get the template reference variable in component?

To get started using template reference variables, simply create a new Angular component or visit an existing one. To create a template reference variable, locate the HTML element that you want to reference and then tag it like so: #myVarName .

What is ngForm and NgModel?

The NgModel is used in form fields and can be exported in local template variable to get its values and validation status in HTML template. When we create HTML form, we have to use name attribute in form fields. In the context of NgForm , the role of NgModel is to register the form field with form using name attribute.


1 Answers

import this -

import {ViewChild} from 'angular2/core';

Just add this field with the annotation to the class

// Dart syntax
@ViewChild('heroForm') NgForm heroForm;

You can't use it in the constructor though because it is only set later. In ngAfterViewInit or event handlers for user input you can use it without limitations.

like image 160
Günter Zöchbauer Avatar answered Oct 06 '22 06:10

Günter Zöchbauer