pen*_*ngz 6 validation angular-material angular
我正在 Angular 8 中使用 Material 和 Reactive Forms 构建一个应用程序。我有一个包含 ItemID、Title 和 Description 字段的反应式表单。
ItemID 字段旁边有一个搜索按钮,用于发送 HTTP 请求以从外部 API 获取数据。这一切正常。但是,在单击搜索按钮并返回响应后,验证会以红色突出显示 Title 和 Description 字段,即使这些字段尚未被触及并且是原始的。由于尚未触及这些字段,因此不应以红色突出显示它们。
下面是应用于窗体控件的类,当它以红色突出显示时,即使它仍然没有被触及和原始。
mat-form-field ng-tns-c9-58 mat-primary mat-form-field-type-mat-input mat-form-field-appearance-outline mat-form-field-can-float mat-form-field-should-float mat-form-field-has-label ng-untouched ng-pristine ng-invalid mat-form-field-invalid
Run Code Online (Sandbox Code Playgroud)
TS组件
constructor(
private fb: FormBuilder
) { }
// Initialize Item Detail form
this.itemDetailForm = this.fb.group({
Item: this.fb.group({
ItemID: [null],
}),
Title: [null, Validators.compose([
Validators.required,
Validators.maxLength(10),
])],
Description: [null, Validators.compose([
Validators.required,
Validators.maxLength(10),
});
Run Code Online (Sandbox Code Playgroud)
HTML 组件
<form [formGroup]="itemDetailForm" (ngSubmit)="onSubmit()">
<div formGroupName="Item">
<mat-form-field appearance="outline" floatLabel="always">
<mat-label>Item ID</mat-label>
<input matInput formControlName="ItemID">
</mat-form-field>
<button mat-raised-button (click)="onItemSearch(this.itemDetailForm.get('ItemID').value)"
[disabled]="itemDetailForm.get('ItemID').invalid">
<mat-icon>search</mat-icon>
</button>
</div>
<mat-form-field appearance="outline" floatLabel="always">
<mat-label>Title</mat-label>
<input matInput formControlName="Title">
</mat-form-field>
<mat-form-field appearance="outline" floatLabel="always">
<mat-label>Description</mat-label>
<input matInput formControlName="Description">
</mat-form-field>
</form>
Run Code Online (Sandbox Code Playgroud)
Max*_*Max 12
这是因为表单元素内的任何按钮默认都会运行一个本地提交函数来验证您的输入。
使用type="button"按钮元素。默认情况下type="submit"
| 归档时间: |
|
| 查看次数: |
2701 次 |
| 最近记录: |