How to get ngForm variable reference in the compon

2019-06-22 06:15发布

问题:

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.

回答1:

import this -

import {ViewChild} from 'angular2/core';

Just add this field with the annotation to the class

@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.