【发布时间】:2018-10-12 11:34:10
【问题描述】:
我在 Angular 6 中工作。我有两个字段和复选框。我为字段名,姓氏放置了反应形式。当用户单击复选框姓氏字段将使用 *ngIf 条件隐藏时,我还有另一种情况。然后我提交表格。验证器不允许我提交表单,因为它被隐藏了。
另一种情况是,如果用户愿意,用户有时可以在字段中输入值。那么在这种情况下,我该如何提交表单呢?
<form [FormGroup]="testFormGroup" (ngSubmit)="onSubmit()">
<label> firstName </label>
<mat-form-field floatLabel="never">
<input matInput placeholder="firstName" formControlName="firstName" required>
<mat-error *ngIf="testFormGroup.get('firstName').hasError('required')">
firstname is required
</mat-error>
</mat-form-field>
<div class="check">
<mat-checkbox (click)="onCheck()"> check </mat-checkbox>
</div>
<div *ngIf="ischeck===true">
<label> lastName </label>
<mat-form-field floatLabel="never">
<input matInput placeholder="lastName" formControlName="lastName" required>
<mat-error *ngIf="testFormGroup.get('lastName').hasError('required')">
lastName is required
</mat-error>
</mat-form-field>
</div>
<button type="submit" name="submit"> submit </button>
</form>
testFormGroup: FormGroup;
createFormGroup() {
this.FormGroup = this._formBuilder.group({
firstname: ['', Validators.required],
lastname: ['', Validators.required],})
}
onSubmit() {
if (this.testFormGroup.invalid) {
console.log('');
return;
}
console.log('form', JSON.stringify(this.testFormGroup.value));
}
isCheck;
onCheck() {
this.isCheck = (this.isCheck === true )? false : true;
}
【问题讨论】:
-
不要用
ngIf从DOM中隐藏它,从表单组中移除表单控件。 -
@ritaj 有时用户可能希望输入该字段。这就是为什么我没有删除它
-
然后在复选框单击时将表单控件返回到表单组...
-
怎么样?请给我一个想法
-
有时我想验证名字和姓氏。有时我只想在用户单击复选框时检查名字。
标签: javascript validation angular5 angular6 angular-reactive-forms