Using Template-driven Forms for Simple Data Handling
Learn to implement template-driven forms in Angular for straightforward data handling and validation, suitable for small-scale applications.
0 likes
164 views
Rule Content
{
"title": "Using Template-driven Forms for Simple Data Handling",
"description": "Implement template-driven forms in Angular for straightforward data handling and validation, suitable for small-scale applications.",
"category": "Angular Cursor Rules",
"rules": [
{
"name": "Import FormsModule",
"description": "Ensure that the FormsModule is imported in your Angular module to enable template-driven forms.",
"code": "import { FormsModule } from '@angular/forms';\n\n@NgModule({\n imports: [\n BrowserModule,\n FormsModule\n ],\n declarations: [\n AppComponent\n ],\n bootstrap: [AppComponent]\n})\nexport class AppModule {}"
},
{
"name": "Use ngModel for Two-Way Data Binding",
"description": "Utilize the ngModel directive to bind form controls to component properties, enabling two-way data binding.",
"code": "<input type=\"text\" id=\"username\" name=\"username\" [(ngModel)]=\"username\" required />"
},
{
"name": "Implement Form Validation",
"description": "Apply built-in validators like required, minlength, and email to form controls to enforce input validation.",
"code": "<input type=\"email\" id=\"email\" name=\"email\" [(ngModel)]=\"email\" required email />"
},
{
"name": "Handle Form Submission",
"description": "Use the ngSubmit directive to handle form submission and process form data in the component.",
"code": "<form (ngSubmit)=\"onSubmit()\">\n <!-- form controls -->\n <button type=\"submit\">Submit</button>\n</form>\n\nexport class AppComponent {\n onSubmit() {\n // Process form data\n }\n}"
},
{
"name": "Display Validation Error Messages",
"description": "Show error messages conditionally based on the validity state of form controls to provide user feedback.",
"code": "<div *ngIf=\"email.invalid && email.touched\" class=\"error-message\">\n <div *ngIf=\"email.errors?.required\">Email is required.</div>\n <div *ngIf=\"email.errors?.email\">Invalid email format.</div>\n</div>"
},
{
"name": "Style Error Messages",
"description": "Apply CSS styles to error messages to enhance user experience and accessibility.",
"code": ".error-message {\n color: red;\n font-size: 12px;\n margin-top: 5px;\n}"
}
]
}