【发布时间】:2015-11-10 18:41:08
【问题描述】:
如何在表单有效之前禁用“提交”按钮?
angular2 是否具有可用于提交按钮的等效 ng-disabled 功能? (ng-disabled 对我不起作用。)
【问题讨论】:
-
仅当您使用中间验证时,例如在打字时。不要这样做.. 仅具有良好的思想或异步验证,例如依赖于后端。
如何在表单有效之前禁用“提交”按钮?
angular2 是否具有可用于提交按钮的等效 ng-disabled 功能? (ng-disabled 对我不起作用。)
【问题讨论】:
正如在这个 Angular example 中看到的那样,有一种方法可以在整个表单有效之前禁用按钮:
<button type="submit" [disabled]="!ngForm.valid">Submit</button>
【讨论】:
ng-form-modal。请他更新thanx。
在 Angular 2.x.x、4、5 ...
<form #loginForm="ngForm">
<input type="text" required>
<button type="submit" [disabled]="loginForm.form.invalid">Submit</button>
</form>
【讨论】:
.html
<form [formGroup]="contactForm">
<button [disabled]="contactForm.invalid" (click)="onSubmit()">SEND</button>
.ts
contactForm: FormGroup;
【讨论】:
这是一个工作示例(您必须相信我,控制器上有一个 submit() 方法 - 如果在输入字段中输入了 'abc',它会打印一个对象,例如 {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>
如你所见:
此外,这是您不使用我推荐的新 FormBuilder 的时候。使用 FormBuilder 时情况大不相同。
【讨论】:
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>
【讨论】:
这对我有用。
newForm : FormGroup;
<input type="button" [disabled]="newForm.invalid" />
【讨论】:
在每个强制输入标签中都包含“required”关键字以使其正常工作,这一点很重要。
<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>
【讨论】:
下面的代码可能会有所帮助:
<button type="submit" [attr.disabled]="!ngForm.valid ? true : null">Submit</button>
【讨论】: