I am working in Angular 6. I have two fields and check box. I put reactive form for fields first-name, last-name. I have another situation when user clicks check box last-name field will be hidden using *ngIf condition. Then I submit the form. The validators do not allow me to submit the form, because it hid.
And another situation is if the user wishes, the user may enter the value in the field sometime. So in this situation, how do I submit the form?
<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, remove the form control from the form group. - Roberto Zvjerković