Open
Description
Which @angular/* package(s) are relevant/related to the feature request?
core
Description
I had a case with dynamic forms that rendered fields based on some conditions. ex:
@if (condition1) {
<field1 />
<field2 />
}
@if (condition2) {
<field1 />
<field3 />
}
and in the component.ts the form looks like this:
@Component({
})
export class SampleComponent {
sampleForm = new FormGroup({
field1: new FormControl({disabled: true}),
field2: new FormControl({disabled: true}),
field3: new FormControl({disabled: true}),
})
}
now these fields have some common configuration that I added in a base class that they can extend from. ex:
export class BaseField {
// Common properties and methods for all form fields
fieldName: string;
constructor(
public controlContainer: ControlContainer,
public destroyRef: DestroyRef,
fieldName: string
) {
this.fieldName = fieldName;
this.destroyRef.onDestroy(() => this.control.disable());
// my work around for not using onInit to avoid overriding the field's onInit
setTimeOut(() => {
this.control.enable()
}, 0)
}
ngOnInit(){} // this will override the field's on init
get form() {
const form = this.controlContainer?.control;
if (!form) {
throw new Error('ControlContainer [Base Form] is not available');
}
return form as FormGroup;
}
get control() {
const control = this.form?.get(this.fieldName);
if (!control) {
throw new Error(`ControlContainer [${this.fieldName}] is not available`);
}
return control;
}
}
Proposed solution
Adding initRef
that works in a similar way to the destroyRef
. ex:
constructor(
public controlContainer: ControlContainer,
public destroyRef: DestroyRef,
public initRef: InitRef,
fieldName: string
) {
this.fieldName = fieldName;
this.destroyRef.onDestroy(() => this.control.disable());
this.initRef.onInit(() => {this.control.enable() }
}
Alternatives considered
I considered adding an abstract onInit function for other devs to fill in their logic in it.
I considered using super.onInit
inside the onInit of each field.
but the main Idea that I do not want to enforce an un-needed line that can be abstracted.