Angular2表单 - 提交按钮已禁用?

时间:2015-08-18 01:09:33

标签: forms angular

在表格有效之前,是否应禁用“提交”按钮?最佳做法?

angular2是否具有可以在“提交”按钮上使用的ng-disabled等效项? (ng-disabled对我不起作用。)

8 个答案:

答案 0 :(得分:203)

在这里看到example,在Angular 2中这是一种禁用按钮的方法,直到整个表单有效:

<button type="submit" [disabled]="!ngForm.valid">Submit</button>

答案 1 :(得分:39)

Angular 2.x.x 4 5 ......

<form #loginForm="ngForm">
    <input type="text" required> 
    <button  type="submit"  [disabled]="loginForm.form.invalid">Submit</button>
</form>

答案 2 :(得分:2)

这是一个工作示例(您必须相信我在控制器上有一个submit()方法 - 如果在输入字段中输入'abc',它会打印一个Object,如{user:'abc'} ):

<form #loginForm="ngForm" (ngSubmit)="submit(loginForm.value)">
    <input type="text" name="user" ngModel required>
    <button  type="submit"  [disabled]="loginForm.invalid">
        Submit
    </button>
</form>

如你所见:

  • 不要使用loginForm.form,只需使用loginForm
  • loginForm.invalid和!loginForm.valid一样有效
  • 如果希望submit()传递正确的值,则input元素应具有name和ngModel属性

此外,这是您不使用我推荐的新FormBuilder。使用FormBuilder时情况就大不相同了。

答案 3 :(得分:2)

Angular 2中的表单验证非常直接

这是一个例子,

<form (ngSubmit)="onSubmit()" #myForm="ngForm">

 <div class="form-group">
  <label for="firstname">First Name</label>
  <input type="text" class="form-control" id="firstname" 
   required [(ngModel)]="firstname" name="firstname">
 </div>

 <div class="form-group">
  <label for="middlename">Middle Name</label>
  <input type="text"  class="form-control" id="middlename" 
   [(ngModel)]="middlename" name="middlename">
 </div>

 <div class="form-group">
  <label for="lastname">Last Name</label>
  <input type="text"  class="form-control" id="lastname" 
   required minlength = '2' maxlength="6" [(ngModel)] = "lastname" name="lastname">
 </div>

 <div class="form-group">
  <label for="mobnumber">Mob Number</label>
  <input type="text"  class="form-control" id="mobnumber"  
   minlength = '2' maxlength="10" pattern="^[0-9()\-+\s]+$" 
   [(ngModel)] = "mobnumber" name="mobnumber">
 </div>

 <button type="submit" [disabled]="!myForm.form.valid">Submit</button>

</form>

Check this plunker for demo

More info

答案 4 :(得分:1)

请务必在每个必填输入标记中包含“必需”关键字才能使其生效。

 <form (ngSubmit)="login(loginForm.value)" #loginForm="ngForm">
    ...
    <input ngModel required name="username" id="userName" type="text" class="form-control" placeholder="User Name..." />
    <button type="submit" [disabled]="loginForm.invalid" class="btn btn-primary">Login</button>

答案 5 :(得分:1)

.html

<form [formGroup]="contactForm">

<button [disabled]="contactForm.invalid"  (click)="onSubmit()">SEND</button>

.ts

contactForm: FormGroup;

答案 6 :(得分:0)

可能在代码下方可以提供帮助:

<button type="submit" [attr.disabled]="!ngForm.valid ? true : null">Submit</button>

答案 7 :(得分:0)

这对我有用。

.TS

let max = Double(judo.text ?? "") ?? 0.0
if counter >= max {
    timer?.invalidate()
    timer = nil
}

html的

newForm : FormGroup;
相关问题