【发布时间】:2020-06-15 11:18:15
【问题描述】:
场景:我有 4 个表单域。
- 说明(可选)
- 选择类型(必填)
- Phone (Required only if Select Type is set to 'Phone')
- 电子邮件(只有选择类型设置为“电子邮件”时才需要)
当我更改选择类型字段时,根据选择,电话字段或电子邮件字段将可见。我需要验证这些字段。
问题:
当表单加载时,它只有描述、选择类型下拉菜单和保存按钮。
第 1 步:在不输入任何内容的情况下单击保存按钮,应该会抛出一个警告说 Select Type is required 并且选择类型将是红色的。
第 2 步:选择一个类型,下一个输入变为可见,带有红色边框。这不应该发生,因为用户没有触及该字段。我该如何解决这个问题?
代码:
html
<div class="example-container">
<form [formGroup]="groupForm" (ngSubmit)="onSubmit()">
<section>
<section class="input-row">
<mat-form-field>
<input matInput type="test" placeholder="Description" id="description" formControlName="description"/>
</mat-form-field>
</section>
<section class="input-row">
<mat-form-field>
<mat-select id="sourceType" formControlName="sourceType" placeholder="Select Type*">
<mat-option value="phone">Phone</mat-option>
<mat-option value="email">Email</mat-option>
</mat-select>
</mat-form-field>
</section>
<section *ngIf="typeIsPhone" class="input-row">
<mat-form-field>
<input matInput type="number" placeholder="Phone" id="phoneValue" formControlName="phoneValue"/>
</mat-form-field>
</section>
<section *ngIf="typeIsEmail" class="input-row">
<mat-form-field>
<input matInput type="email" placeholder="Email" id="emailValue" formControlName="emailValue"/>
</mat-form-field>
</section>
</section>
<button mat-raised-button color="primary" type="submit" class="save">
Save
</button>
</form>
</div>
组件:
export class FormFieldOverviewExample implements OnInit {
typeIsPhone = false;
typeIsEmail = false;
public groupForm: FormGroup = new FormGroup({
description: new FormControl(""),
sourceType: new FormControl("", [Validators.required]),
phoneValue: new FormControl("", [Validators.required]),
emailValue: new FormControl("", [Validators.required])
});
constructor() {}
ngOnInit(): void {
this.groupForm
.get("sourceType")
.valueChanges.subscribe(this.setSourceType.bind(this));
}
setSourceType(SourceType: string) {
this.typeIsPhone = SourceType === "phone";
this.typeIsEmail = SourceType === "email";
}
onSubmit() {
const sourceTypeFormControl = this.groupForm.get("sourceType");
const phoneEnteredFormControl = this.groupForm.get("phoneValue");
const emailEnteredFormControl = this.groupForm.get("emailValue");
if (sourceTypeFormControl.errors.required) {
alert("Source Type is required!");
return;
} else {
if (phoneEnteredFormControl.errors.required) {
alert("Phone is required!");
return;
}
if (emailEnteredFormControl.errors.required) {
alert("email is required!");
return;
}
}
}
}
【问题讨论】:
-
您可以通过
pristine属性检查用户是否更改了formControl的值 -
我尝试使用
markaspristine和markasuntouched。该字段仍显示为红色 -
只要检查formControl是否为
pristine,如果是则显示错误并且无效。
标签: angular validation angular-reactive-forms angular2-form-validation