我需要为角度表单添加验证,以确保用户不会将表单提交为空进行编辑操作,我没有使用formBuilder,我希望找到没有formBuilder或formgroup的解决方案。我的html代码是:
<div class="container p-0">
<div class="row justify-content-center">
<div class="col-lg-10">
<div class="card" *ngIf="currentForm">
<h4 class="card-header"> Edit Subscriber </h4>
<div class="card-body">
<form>
<div class="addForm">
<div class="form-group">
<label for="subscriberName">Subscriber Name</label>
<input type="text" id="subscriberName" #subscriberName="ngModel" name="subscriberName" [(ngModel)]="currentForm.subscribers.subscriber[0].subscriberName" class="form-control" required minlength="1" maxlength="100">
<div [hidden]="subscriberName.valid || subscriberName.pristine"
class="alert alert-danger"> Name is required</div>
</div>
<div class="button">
<button type="submit" routerLink="/viewsubscriber" class="btn btn-primary (click)="onSubmit()">Update</button> </div>
</form>
</div>
</div>
</div>
</div>
还有我的ts代码:onSubmit() {
this.submitted = true;
let requestBody={subscriberName: this.currentForm.subscribers.subscriber[0].subscriberName }
console.log(requestBody);
this.userService.editSubscriber(this.currentForm.subscribers.subscriber[0].subscriberId,requestBody)
.subscribe(
_response => { const confirmDialog = this.dialog.open(ConfirmDialogComponent, {
data: {
title: 'info',
message: 'subscriber edited successfuly '
}
});
只需将onSubmit
方法中的if
条件放在顶部即可。
onSubmit() {
if (!this.currentForm.subscribers.subscriber[0].subscriberName) {
console.log('name required');
return false;
}
this.submitted = true;
let requestBody={subscriberName: this.currentForm.subscribers.subscriber[0].subscriberName }
console.log(requestBody);
this.userService.editSubscriber(this.currentForm.subscribers.subscriber[0].subscriberId,requestBody)
.subscribe(
_response => { const confirmDialog = this.dialog.open(ConfirmDialogComponent, {
data: {
title: 'info',
message: 'subscriber edited successfuly '
}
});
}
如果表单具有必需的控件,则可以使用表单的valid
属性来检查是否所有内容都正确。在提交按钮上添加[disabled]="!currentForm.valid"
,如下所示:
<button routerLink="/viewsubscriber" class="btn btn-primary [disabled]="!currentForm.valid">
Update
</button>
此外,将[formGroup]="currentForm"
和(ngSubmit)="onSubmit()"
放在<form>
标记上,并从提交按钮中删除(click)
事件。