Angular Forms are a powerful feature of the Angular framework that allow you to easily capture user input and validate it before submitting it to the server. There are two types of forms in Angular: Template-driven forms and Reactive forms.
Template-driven forms use directives to bind form controls to properties on a model object. They are easy to use and require less boilerplate code. Here is an example of a template-driven form in Angular:
<form #myForm="ngForm" (ngSubmit)="onSubmit(myForm.value)">
<label>
Name:
<input type="text" name="name" ngModel required>
</label>
<label>
Email:
<input type="email" name="email" ngModel required>
</label>
<button type="submit">Submit</button>
</form>
In this example, we have a simple form that asks the user for their name and email address. The ngForm directive is used to create a form instance, and the ngModel directive is used to bind form controls to properties on the component. The required attribute is used to ensure that the form controls are not empty.
The ngSubmit event is used to handle the form submission. When the user clicks the Submit button, the onSubmit method is called with the form value as an argument.
Here is an example of how to handle the form submission in the component:
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: `
<form #myForm="ngForm" (ngSubmit)="onSubmit(myForm.value)">
<label>
Name:
<input type="text" name="name" ngModel required>
</label>
<label>
Email:
<input type="email" name="email" ngModel required>
</label>
<button type="submit">Submit</button>
</form>
`,
})
export class AppComponent {
onSubmit(formData) {
console.log(formData);
// Do something with the form data
}
}
In this example, the onSubmit method is called with the form data as an argument when the user clicks the Submit button. You can then use this data to perform some action, such as sending it to the server.
Overall, template-driven forms are easy to use and require less boilerplate code, but they have some limitations when it comes to complex forms. Reactive forms, on the other hand, are more powerful and flexible, but require more code to set up.
Top comments (0)