I have two components Parent and Child.
Parent stores the state of the formGroup used in the child component. Each time I receive new data from external source, I pass this data through template and construct new FormGroup and decide based on one property if FormGroup is enabled or disabled. New data are changed as I want but the disabled/enabled state does not.
My code:
Child component
@Input() edvForm: FormGroup;
@Input() isBlocMainSupport: boolean;
@Input() data: Data;
ngOnChanges(changes: SimpleChanges): void {
this.setForm();
}
setForm() {
...
this.edvForm.addControl(
'supportType',
new FormControl({ value: supportType, disabled: !this.isBlocMainSupport })
);
}
Parent component
edvForm: FormGroup;
isBlocMainSupport = true;
data: Data;
...
ngOnInit(): void {
this.sourceEvent$
.pipe(takeUntil(this.destroy$))
.subscribe(newData => {
this.newGraphicElements([newData]);
});
}
...
newGraphicElements(newData: Data[]) {
this.reset();
...
this.data = newData[0];
this.isBlocMainSupport = myCondition ? true : false;
}
...
reset() {
this.edvForm = new FormGroup({});
}
Parent template
<child-comp
*ngIf="isTheRightChild"
[data]="data"
[edvForm]="edvForm"
[isBlocMainSupport]="isBlocMainSupport"
></child-comp>
To resume, data are well passed and change everytime as needed. But, disable state is not applied with : "disabled: !this.isBlocMainSupport"
I found the solution on github: formGroup disable()/enable() does not work right after init #22556
The problem is the change detector. The following code is working :
this.changeDetector.detectChanges(); // use it before using disable/enable
this.form.controls['name'].disable();