I'm facing a challenge with a complex form where the fields depend on toggling checkboxes in a separate component (parent). My goal is to dynamically validate the form, with some fields being enabled and others disabled based on the toggling of the checkboxes. I've experimented with various examples without success...
parent.component.html
<input type="checkbox" id="check" ng-model="checked" (click)='toggleCheckform()'>
<label for="check">Check me</label>
<mat-tab label="child">
<child [isCheck]="toggleCheck" (messageToEmit)="getMessage($event)"></child>
</mat-tab>
parent.component.ts
export class ParentComponent {
constructor() { }
toggleCheck: boolean = false;
ngOnInit() {
}
toggleCheckform() {
this.toggleCheck = !this.toggleCheck;
}
}
child.component.ts
export class ChildComponent {
@Input() isCheck: boolean;
testForm = this.fb.group({
Field1: ['', Validators.required],
Field2: ['', Validators.required]
});
get Field1() { return this.testForm.get('Field1'); }
get Field2() { return this.testForm.get('Field2'); }
if(isCheck){
this.testForm.get('Field1').disable();
}
onSubmit() {
// TODO: Use EventEmitter with form value
console.warn(this.testForm.value);
}
constructor(private fb: FormBuilder) {
}
ngOnInit() {
}
child.component.html
<form [formGroup]="testForm" (ngSubmit)="onSubmit()">
<div *ngIf="isCheck">
<div class="form-group">
<label for="Field1">Field1</label>
<input type="text" class="form-control" id="Field1" formControlName="Field1">
</div>
</div>
<div class="form-group">
<label for="Field2">Field2</label>
<input type="text" class="form-control" id="Field2" formControlName="Field2">
</div>
</form>
My goal is to dynamically enable or disable form fields for validation based on the checkbox on the parent component. While the form works initially, it fails to update dynamically. Any assistance would be appreciated.