Angular 2表单验证无效

时间:2016-08-23 18:19:18

标签: angular angularjs-ng-form

我有一个角度2应用程序(RC.4),我遇到表单验证问题。

我的模板中有以下表单代码。

<div class='modal'>
    <form #modalForm='ngForm'>
      <div class='heading'>
        <h4>{{_title}}</h4>
        <div class='close-icon' (click)='close()'></div>
      </div>
      <div class='body'>
        <input type='text' name='projectName' [(ngModel)]='projectName' required placeholder='Give your project a name...' id='focusOnMe'>
      </div>
      <div class='controls'>
        <button class='btn btn-secondary' (click)='close()'>Cancel</button>
        <button type='submit' class='btn' (click)='sendAction()' [disabled]='!modalForm.form.valid'>{{_action}}</button>
      </div>
    </form>
  </div>

正如你所看到我命名表单元素并将其设置为ngForm,然后在输入中我包含了必需的属性,最后在提交按钮上我说[disabled] =!modalForm.form.valid但是由于某种原因即使所需输入为空,表单也始终标记为有效。我在这里缺少什么?

1 个答案:

答案 0 :(得分:0)

对于Angular 2 RC 4:

您缺少告诉表单您的&#34; projectName&#34;输入应该是表单验证的一部分。只需添加&#34; ngControl =&#39; inputId&#39;&#34;:

<input type='text' 
       name='projectName' 
       ngControl="projectName" 
       [(ngModel)]='projectName' 
       required 
       placeholder='Give your project a name...' 
       id='focusOnMe'>

对于Angular 2.0决赛:

  1. 将[formGrooup]添加到表单中:
  2. <form [formGroup]="modalForm">

    1. 添加&#34; formControlName&#34;对你的控制:

      <input type='text' name='projectName' formControlName="projectName" [(ngModel)]='projectName' required placeholder='Give your project a name...' id='focusOnMe'>