<form [formGroup]="userForm" (ngSubmit)="onSubmit()" novalidate>
First Name:
<input type="text" formControlName="first_name"/>
<span *ngIf="userForm.controls.first_name.touched && userForm.controls.first_name.errors?.required">
Please first name.!
</span>
<br>
Last Name:
<input type="text" formControlName="last_name"/>
<span *ngIf="userForm.controls.last_name.touched && userForm.controls.last_name.errors?.required">
Please enter last name.!
</span>
<br>
Do you have child?
<input type="checkbox" (change)="isChildChange($event)" formControlName="isAnyChild"/>
<br>
<ng-container *ngIf="userForm.value.isAnyChild">
Child Name:
<input type="text" formControlName="child_name"/>
<span *ngIf="userForm.controls.child_name.touched && userForm.controls.child_name.errors?.required">
Please enter child name.!
</span>
</ng-container>
<br>
<input type="submit" [disabled]="!userForm.valid"/>
</form>
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormControl, Validators, FormArray } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
userForm: FormGroup;
constructor() {
this.userForm = new FormGroup({
first_name: new FormControl('', [Validators.required]),
last_name: new FormControl('', [Validators.required]),
isAnyChild: new FormControl('',),
child_name: new FormControl('')
});
}
onSubmit() {
if(this.userForm.valid) {
console.log(this._v());
}
}
_v() {
return this.userForm.value;
}
setRequired() {
return [Validators.required];
}
isChildChange(event) {
if(this.userForm.value.isAnyChild) {
this.userForm.controls.child_name.setValidators(this.setRequired());
} else {
this.userForm.controls.child_name.clearValidators();
}
}
}