In Angular, you can submit a form using the (ngSubmit) directive. Here's an example:
First, create a form in your template using the ngForm directive:
<form #myForm="ngForm" (ngSubmit)="onSubmit(myForm)"> <label for="name">Name:</label> <input type="text" id="name" name="name" ngModel> <label for="email">Email:</label> <input type="email" id="email" name="email" ngModel> <button type="submit">Submit</button> </form>
In this example, we're using the ngForm directive to create a form and
binding it to a template reference variable #myForm. We're also using the
ngModel directive to bind the input fields to properties in our component.
Next, we're using the (ngSubmit) directive to call a function called onSubmit() when the form is submitted. We're passing the myForm variable to the function, which contains the form data.
In our component, we can define the onSubmit() function to handle the form submission:
import { Component } from '@angular/core'; @Component({ selector: 'my-component', template: ` <form #myForm="ngForm" (ngSubmit)="onSubmit(myForm)"> <label for="name">Name:</label> <input type="text" id="name" name="name" ngModel> <label for="email">Email:</label> <input type="email" id="email" name="email" ngModel> <button type="submit">Submit</button> </form> ` }) export class MyComponent { onSubmit(form: NgForm) { // Do something with the form data console.log(form.value); } }
In this example, we're defining the onSubmit() function in our component. The function takes the myForm variable as a parameter, which contains the form data. We can then do whatever we need to do with the form data, such as sending it to a server or updating our component's state.
That's it! With this setup, pressing the "Submit" button in the form will trigger the onSubmit() function, which will handle the form submission.
Comments
Post a Comment