I have a form which consist of a checkbox and a component named address. So whenever user click the checkbox app should set the address to required field. This is my HTML.
<form [formGroup]="registerForm">
<app-address-input formControlName="address"></app-address-input><br>
<input type="checkbox" formControlName="check"> Check?
</form>
<p>Form value: {{ registerForm.value | json }}</p>
<p>Form status: {{ registerForm.status | json }}</p>
This is my component
export class AppComponent implements OnChanges {
registerForm = new FormGroup({
address: new FormControl(undefined),
check: new FormControl(undefined)
});
get address() {
return this.registerForm.get('address')
}
get check() {
return this.registerForm.get('check')
}
ngOnChanges() {
this.registerForm.get('check').valueChanges.pipe(tap(val => {
if(val){
this.registerForm.get('address').setValidators(Validators.required)
}
this.registerForm.get('address').updateValueAndValidity();
})).subscribe();
}
}