Using form parent properties in transformFrom/To
See original GitHub issueHi there,
i just migrated my application from the old to the new api. A few forms behaved differently after the migration but i found the issue quickly. I know that this is not really a bug but i still want to share it and maybe spark a discussion.
angular@13 ngx-sub-form@5.3.2
With the old inheritance-based api i was able to pass additional data via @Input()
into my component and since my component extended NgxAutomaticRoot/NgxRoot/NgxSubFormComponent i could use this data inside the transformToFormGroup and transformFromFormGroup functions.
@Input('configurations')
public configurations: Configuration[] = [];
...
protected transformToFormGroup(client: Client | null, defaultValues: Partial<ClientForm> | null): ClientForm | null {
if (!client) {
return null;
}
const configuration = this.configurations.find((configuration) => configuration.id === client.configurationId) ?? null;
return {
name: client.name,
configuration: configuration,
};
}
So after migrating to the new api all the forms which had such additional @Input
properties failed because this
simply is in the wrong context when transformToFormGroup is called, thus this.configurations
is undefined.
In order to fix this i had to wrap my transformToFormGroup inside a construction function which accepts and keeps backreference to my component. Think of it as a common var that = this;
situation.
interface TransformFunc {
(client: Client | null): ClientForm | null;
}
...
private backReferencedTransformToFormGroup = ( backreference: any ): TransformFunc => {
return (client: Client | null): ClientForm | null => {
if (!client) {
return null;
}
const configuration = backreference.configurations.find((configuration) => configuration.id === client.configurationId ) ?? null;
return {
name: '',
configuration: configuration,
};
};
};
...
public form = createForm<Client, ClientForm>(this, {
...
toFormGroup: this.backReferencedTransformToFormGroup(this),
});
Check a full example at https://stackblitz.com/edit/angular-ivy-t8fvta
Unsurprisingly this is also the case for transformFromFormGroup and i can even think of a lot more cases where a backreference is needed since it is not an @Input()
-dependent problem but applies to all cases where a transformFunction needs access to the actual component properties.
Depending on the use-case/complexity one could also do this kind of mapping/transformation in the parent-component and not the form-component. But i suppose that’s why ngx-subform allows us to define a function for toFormGroup and fromFormGroup in the first place.
Issue Analytics
- State:
- Created 9 months ago
- Comments:5
Top GitHub Comments
Yes, closing this issue is totally fine. Thanks for reaching out again!
Oh yes, well spotted! I think it’s now ok to close this issue as you’ve got your answer?