Revised Response
The FormControl's controls are not directly located within the FormGroup class, but rather inside a property called controls
.
To add controls to the extending class, you can simply manipulate the controls property.
export class ExtendedFormGroup extends FormGroup {
constructor(
controls: { [k: string]: AbstractControl },
validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions,
asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[]
) {
super({...controls, alwaysPresent: new FormControl()},
validatorOrOpts,
asyncValidator
);
this.addExtendedProperties();
}
addExtendedProperties() {
this.controls["additional_control"] = new FormControl("");
}
}
In summary:
- Pass the constructor argument into the super method and include an additional always present control item.
- Directly modify the
controls
property as stated in the original inquiry.
By creating a new instance of ExtendedFormGroup({})
, you will now have a FormGroup with two predefined controllers: alwaysPresent
and additional_control
.
Prior Solution
JavaScript, and thus TypeScript, treat classes as labeled blocks with prototypes, allowing for square bracket notation to access properties within the class scope using this
.
class Parent {
foo: string;
constructor(foo: string) {
this.foo = foo;
}
}
class Child extends Parent {
constructor(foo: string) {
super(foo);
this.assignPropertiesDirectly();
}
assignPropertiesDirectly() {
this["bar"] = "Creates 'bar' on Child";
this["foo"] = "overwrites foo with this text";
}
}
However, this approach is fragile and negates the advantages of TypeScript, relying on string-based property names which can lead to maintenance challenges or errors. Consider exploring composition design for a better solution.