angular
angular copied to clipboard
Add convenience methods to eliminate control getters
Which @angular/* package(s) are relevant/related to the feature request?
forms
Description
Oftentimes when working with reactive forms, we need to create control getters in order to be able to get a reference to AbstractControl
with a coercion to a more specific type:
get myArrayCtrl(){
return this.form.get('path.to.control') as FormArray
}
<div *ngFor="let control of myArrayCtrl.controls; let i = index">
...
</div>
This happens usually when working with FormArrays, but also when you need a[formGroup]
in order to be able to use formControlName
in ng-template
(Error: NG01050: formControlName must be used with a parent formGroup directive.). Unfortunately, in the template it doesn't seem possible to provide the coercion, so we need to go and create a getter.
With just one getter this might not be a big deal, but with complex forms every single getter contributes to unnecessary boilerplate code. Sometimes you need to use the reference in multiple places, so making a getter might actually make a lot of sense, but for just one instance creating a getter feels superficial.
Proposed solution
Therefore, I would propose (assuming that this is feasible at all) that reactive forms provide a collection of convenience methods getFormGroup | getFormArray | getFormControl | getFormRecord
which internally would do the necessary coercion and could be used directly within templates:
<ng-template [formGroup]="form.getFormGroup('path.to.form.group')">
...
</ng-template>
<div *ngFor="let control of form.getFormArray('my.array').controls; let i = index">
...
</div>
(or getAsFormGroup | ...
etc)
This would eliminate the getters and slim our code a bit.
Alternatives considered
Let's make the alternative obsolete.
This feature request is now candidate for our backlog! In the next phase, the community has 60 days to upvote. If the request receives more than 20 upvotes, we'll move it to our consideration list.
You can find more details about the feature request process in our documentation.
Just a heads up that we kicked off a community voting process for your feature request. There are 20 days until the voting process ends.
Find more details about Angular's feature request process in our documentation.
Thank you for submitting your feature request! Looks like during the polling process it didn't collect a sufficient number of votes to move to the next stage.
We want to keep Angular rich and ergonomic and at the same time be mindful about its scope and learning journey. If you think your request could live outside Angular's scope, we'd encourage you to collaborate with the community on publishing it as an open source package.
You can find more details about the feature request process in our documentation.