Angular 使用ngsubmit=";onSubmit();
即使必填字段为空,也会保存表单详细信息。我试着禁用按钮,但没有任何效果 这是我的源代码 HTMLAngular 使用ngsubmit=";onSubmit();,angular,forms,requiredfieldvalidator,Angular,Forms,Requiredfieldvalidator,即使必填字段为空,也会保存表单详细信息。我试着禁用按钮,但没有任何效果 这是我的源代码 HTML <form [formGroup]="userForm" (ngSubmit)="onSubmit()" #myForm="ngForm"> <mat-form-field class="example-full-width" style="margin-left:20px"> <input matInput placehol
<form [formGroup]="userForm" (ngSubmit)="onSubmit()" #myForm="ngForm">
<mat-form-field class="example-full-width" style="margin-left:20px">
<input matInput placeholder="Full Name" formControlName="userName" name="userName" required>
<mat-hint> eg:Harry Potter</mat-hint>
</mat-form-field>
<mat-form-field hintLabel="Max 10 characters" style="margin-left:20px">
<input matInput #input maxlength="10" placeholder="Enter your phone number" formControlName="userPhone" name="userPhone"
required>
<mat-hint align="end">{{input.value?.length || 0}}/10</mat-hint>
</mat-form-field>
<br>
<mat-form-field class="example-full-width" style="margin-left:20px">
<input matInput placeholder="Email" [formControl]="userEmail" required="required">
<mat-error *ngIf="userEmail.hasError('email') && !userEmail.hasError('required')">
Please enter a valid email address
</mat-error>
<mat-error *ngIf="userEmail.hasError('required')">
Email is <strong>required</strong>
</mat-error>
</mat-form-field>
<mat-form-field class="example-full-width" style="margin-left:20px">
<input matInput placeholder="Address" formControlName="userAddress" name="userAddType" required>
</mat-form-field>
<mat-form-field class="example-full-width" style="margin-left:20px">
<input matInput placeholder="Type of address" formControlName="userAddType" name="userAddType">
<mat-hint>eg: Home, Work</mat-hint>
</mat-form-field>
<br>
<button style="background-color:darkorange;border-radius: 8px;height:50px;margin-left:60px">
Save and Deliver</button>
</form>
如何验证表单,使其在必填字段不为空之前不保存表单详细信息?您可以在表单中使用验证程序,如下所示:
this.form= this.fb.group({
name: new FormControl('', Validators.required),
surname: new FormControl('', Validators.required),
email: new FormControl('', Validators.required)
});
并尝试禁用“提交”按钮,
<div class="text-center">
<button type="submit" [disabled]="!form.valid" class="btn btn-primary">Submit</button>
</div>
提交
因为您的onSubmit没有检查您的表单是否有效。
它实际上只保存数据
请在onsubmit()中检查您的表单是否有效
或者在html块中添加这种验证。
执行此操作时,即使输入了所有字段,按钮仍将保持禁用状态。这将起作用。我不知道发生了什么。您可以更新问题中的ts代码吗?这似乎是反应式表单和模板驱动表单的混合。你能发布你的userForm
定义吗?您是否尝试过保存并交付
<div class="text-center">
<button type="submit" [disabled]="!form.valid" class="btn btn-primary">Submit</button>
</div>
ex) formName.valid(); // this is for reactive form
onSubmit() {
this.submitted = true;
// stop here if form is invalid
if (this.registerForm.invalid) {
return;
}
alert('SUCCESS!! :-)')
}
<div *ngIf="name.invalid && (name.dirty || name.touched)"
class="alert alert-danger">