我有一个角度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但是由于某种原因即使所需输入为空,表单也始终标记为有效。我在这里缺少什么?
答案 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决赛:
<form [formGroup]="modalForm">
添加&#34; formControlName&#34;对你的控制:
<input type='text'
name='projectName'
formControlName="projectName"
[(ngModel)]='projectName'
required
placeholder='Give your project a name...'
id='focusOnMe'>