I've got a strange error...
I generate dynamic components in the template (a few).
Some of them has property form, which is the FormGroup created via FormBuilder, along with isValid() method.
isValid() returns boolean that depends on this.form.valid value.
The last dynamic component is always responsible for saving data.
It has save() method that:
- Loads all generated dynamic components
- Checks if they have
isValid()method - Then calls above method
It works pretty good! But sometimes... I get an error in the console, that says form is undefined.
What's the problem? Some async stuff?
Wrong hook in the dynamic components? I use ngOnInit() for assigning form property...
SOME CODE PARTS AS EXAMPLE
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 other component's valid status:
@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;
}
}
});
}
}
}