How to get ngForm variable reference in the component class?

谁说胖子不能爱 提交于 2019-12-12 10:45:17

问题


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.



来源:https://stackoverflow.com/questions/34820706/how-to-get-ngform-variable-reference-in-the-component-class

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