Inline vs Separate form control creation in Angular
April 4, 2025 2:15 PM
The difference between the two approaches lies in how the FormControl instances are created and accessed:
https://gist.github.com/amrohit/565aa12c4fa221b02948f78cc895209a
Direct Access:
- You can directly access the FormControl instances (username and email) in the component without needing to reference the FormGroup.
Use Case:
- This approach is useful when you need to frequently interact with individual form controls in the component (e.g., for validation, dynamic updates, or custom logic).
Comparison
Feature | Separate Declaration (Approach 1 ) | Inline Declaration (Approach 2 ) |
---|---|---|
Code Reusability | Allows reuse of FormControl instances. | No reuse; controls are tied to the FormGroup. |
Direct Access | Access controls directly via properties. | Access controls via FormGroup.get(). |
Readability | Slightly more verbose. | More concise and compact. |
Use Case | When controls need frequent interaction. | When controls are only used in the form. |
Which One to Use?
Use Approach 1:
- If you need to frequently interact with individual controls in the component.
- For example, dynamically enabling/disabling a control or applying custom logic.
Use Approach 2:
- If the controls are only used within the form and don't require frequent interaction in the component.
- For example, simple forms with minimal custom logic
If you remember about our password validator which we created some days back while working on the Angular Template Driven Form,
https://gist.github.com/amrohit/95a50e219d02dce3db85ade9265b2a0f
You can recall that we also have had to create a directive "password-strength.directive.ts" in order to use this password validator in our template. But here we do not need to do anything like that.
password: new FormControl('', {
validators: [
Validators.required,
Validators.minLength(6),
passwordStrengthValidator(8),
],
}),
Feature: Also let's say you want the username field update itself when you click away from it or in other sense when the field is blur. We can use this in a case where we want to make a backend call and only then wants to validate this field.
username = new FormControl('', {
validators: [Validators.required],
updateOn:ā'blur', //'change', 'submit'
});
Comments