top of page

Anguler - To get values from a form using Angular CLI

  1. Create a form in your Angular component's template. For example, in your HTML file, add the form element and input fields:

<form (ngSubmit)="onSubmit()">
  <label for="name">Name:</label>
  <input type="text" id="name" name="name" [(ngModel)]="formData.name" />

  <label for="email">Email:</label>
  <input type="email" id="email" name="email" [(ngModel)]="formData.email" />

  <button type="submit">Submit</button>
</form>
  1. In your component class, define a property to store the form data. For example, in your TypeScript file, declare a property called formData:

export class YourComponent {
  formData = {
    name: '',
    email: ''
  };

  onSubmit() {
    // Access the form data here
    console.log(this.formData);
    // You can perform further actions with the form data, like sending it to an API
  }
}

  1. In the onSubmit() method, you can access the form data by referring to the formData property, which is bound to the input fields using [(ngModel)].

  2. When the form is submitted, the onSubmit() method is called. You can perform further actions with the form data, such as sending it to an API, validating it, or updating the component's state.

Note: To use [(ngModel)], you need to import the FormsModule from @angular/forms in your module file and add it to the imports array.

import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';

@NgModule({
  imports: [
    FormsModule
  ],
  // ...
})
export class YourModule { }

That's it! You can now retrieve the values from a form using Angular CLI by binding the form input fields to properties in your component class and accessing the form data in the onSubmit() method.

Related Posts

See All

Comments


bottom of page