In this blog post, we’ll explore a common issue faced by developers while working with Angular forms, specifically when dealing with nested form controls and validation. We’ll use a real-life example to illustrate the problem and discuss the solutions to fix the error: TypeError: Cannot read property ‘errors’ of undefined.
Problem Description
Consider an Angular form with basic personal data, including two nested elements, like the following JSON:
{ "FirstName": "Tom", "LastName":"Hanks", "User": { "Username": "TestAdres", "EMail": "[email protected]" }, "Address": { "City": "Miami", "Street": "Bugatti", "ZipCode": "123-123", "HouseNumber" : "5b" } }
While the form validation works fine for the non-nested fields, such as FirstName and LastName, it’s not working for the nested form controls like User and Address. The error that appears is: TypeError: Cannot read property ‘errors’ of undefined.
Solutions
There are a few possible ways to fix this issue:
- Move the
ngOnInit
code to the component constructor. - Use the
?.
syntax in the[ngClass]
statements. This is also known as the safe navigation operator (check the official Angular documentation). - Prepare an empty
f
object in the constructor with all fields empty and fill them up later, similar to the solution provided in this StackOverflow answer.
For example, you can fix the issue by modifying the way you reference the form controls in your HTML:
Email is required
Conclusion
By adopting one or more of the solutions mentioned above, you can resolve the TypeError: Cannot read property ‘errors’ of undefined issue in Angular forms with nested form controls. This will ensure that your form validations work smoothly for all fields, whether nested or not. Remember, understanding the cause of the error and knowing the right way to handle form controls is crucial for creating robust Angular applications.