I've encountered a perplexing issue...
In my template, I dynamically generate multiple components.
Some of these components have a property called form
, which is a FormGroup
created using the FormBuilder
, and it includes an isValid()
method.
The isValid()
method returns a boolean value based on the validity of this.form.valid
.
The final dynamic component is responsible for saving data. It contains a save()
method that:
- Loads all dynamically generated components
- Checks if they have an
isValid()
method - Calls the above method if available
Everything seems to be working smoothly! However, there are sporadic instances where I encounter an error in the console stating that form
is undefined.
What could be causing this issue? Could it be related to asynchronous operations?
Perhaps there's an incorrect hook in the dynamic components? Currently, I use ngOnInit()
to assign the form
property...
SOME CODE EXAMPLES
Example of a Dynamic Component:
@Component({
selector: 'app-ccapplication-verification',
templateUrl: './ccapplication-verification.component.html',
styleUrls: ['./ccapplication-verification.component.scss']
})
export class CCApplicationVerificationComponent implements OnInit, OnDestroy {
constructor(private workflowService: WorkflowService) { }
public form: FormGroup;
public displayErrors = false;
ngOnInit(): void {
this.form = new FormGroup({});
}
public isValid(): boolean {
const isValid: boolean = this.form.valid; // ERROR: can't get valid of undefined
if (isValid) {
this.displayErrors = false;
return true;
} else {
this.displayErrors = true;
return false;
}
}
}
Dynamic Component that Checks Validity of Other Components:
@Component({
selector: 'app-save-workflow',
templateUrl: './save-workflow.component.html',
styleUrls: ['./save-workflow.component.scss']
})
export class SaveWorkflowComponent implements OnInit {
constructor(private workflowService: WorkflowService) { }
msg: string;
ngOnInit(): void {}
onSave() {
this.msg = '';
let components = this.workflowService.getComponents();
let isError:boolean = false;
components.forEach((comp: any) => {
if(typeof comp['isValid'] === 'function') {
if(!comp.isValid()) { /* HERE I GET ERROR SOMETIMES */
this.msg = 'some text';
isError = true;
}
}
});
}
}
}