[英]Angular => Reactive Forms : disable button when it encounters an empty input field
What is the Reactive Forms way to disable the button, when for instance, in a form, an empty input field is met?什么是响应式 Forms 禁用按钮的方式,例如,在表单中遇到空输入字段时?
So in others words, when all the fields have to be fulfilled in order to enable the button?所以换句话说,什么时候必须填写所有字段才能启用按钮?
I do know that for the TemplateDriven way, it is something like that:我确实知道对于 TemplateDriven 方式,它是这样的:
<div class="row mt-5">
<div class="col-md-6 mx-auto">
<h2 class="text-center">Add Article</h2>
<div class="card mt-3">
<div class="card-body">
<form [formGroup]="articleForm" (ngSubmit)="addArticle()">
<div class="form-group">
<label>Title</label>
<input type="text" formControlName="title" [(ngModel)]="title" class="form-control"
[ngClass]="{ 'is-invalid': submitted && articleForm.controls.title.errors }"/>
<div *ngIf="submitted && articleForm.controls.title.errors" class="text-danger">
<div *ngIf="articleForm.controls.title.errors.required">Title is required</div>
<div *ngIf="articleForm.controls.title.errors.minlength">At least 3 characters</div>
<div *ngIf="articleForm.controls.title.errors.maxlength">Cannot exceed 10 characters</div>
</div>
</div>
<div class="form-group">
<label>Description</label>
<input type="text" formControlName="description" [(ngModel)]="description" class="form-control"
[ngClass]="{ 'is-invalid': submitted && articleForm.controls.description.errors }"/>
<div *ngIf="submitted && articleForm.controls.description.errors" class="text-danger">
<div *ngIf="articleForm.controls.description.errors.required">Description is required</div>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary col-md-4" [disabled]="!title || !description">Add</button>
<a [routerLink]="['/']">
<button type="submit" class="btn btn-primary col-md-4 ml-1">Back</button>
</a>
</div>
</form>
</div>
</div>
</div>
</div>
We need to provide an [(ngModel)] to the inputs fields:我们需要为输入字段提供一个 [(ngModel)]:
[(ngModel)]="title"
[(ngModel)]="description"
and then on the button we can check for the event that way:然后在按钮上,我们可以通过这种方式检查事件:
[disabled]="!title || !description"
And it does work.它确实有效。
However I am mixing formControlName and ngModel , which is not recommended.但是我混合了 formControlName和ngModel ,这是不推荐的。 So I was wondering, how to make it work in a Reactive Form way?所以我想知道,如何使它以反应形式工作?
Please take care of yourself.请好好照顾自己。
You can remove the ngModel.您可以删除 ngModel。
To have your button disabled if the form is invalid you should do it like so:如果表单无效,要禁用您的按钮,您应该这样做:
<button type="submit"[disabled]="articleForm.invalid">Add</button>
I assume you have the code in place in the ts file with the validators in place.我假设您已在 ts 文件中放置了代码,并且已放置了验证器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.