Translate

Saturday 17 February 2024

How to setup Template Driven Forms Angular ?77

 How to setup Template Driven Forms Angular ?


Setting up Template-driven forms in Angular offers a simpler approach for capturing user input in your applications. Here's a step-by-step guide:

1. Install necessary modules:

Make sure you have the FormsModule imported in your app module or the specific feature module where you'll use the form:


TypeScript

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

@NgModule({
  // ... other imports
  imports: [
    // ... other modules
    FormsModule
  ],
  // ... other declarations
})
export class AppModule {}

2. Create your form template:

Use HTML elements like <input>, <select>, and <textarea> to represent your form fields. Bind them to data properties in your component using the ngModel directive:


HTML

<form #myForm="ngForm">
  <div>
    <label for="name">Name:</label>
    <input type="text" id="name" [(ngModel)]="user.name" name="name" required>
  </div>
  <div>
    <label for="email">Email:</label>
    <input type="email" id="email" [(ngModel)]="user.email" name="email" required>
  </div>
  <button type="submit">Submit</button>
</form>

3. Define your component class:

  • Import the FormsModule in your component's module if not already done.

  • Create a property to store the form data (e.g., user: { name: string, email: string }).

  • Access the form element using a template reference variable (#myForm).

  • Implement a handler for the form submission event (e.g., onSubmit()) to access the form data and perform actions.


TypeScript

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

@Component({
  selector: 'app-my-form',
  templateUrl: './my-form.component.html',
  styleUrls: ['./my-form.component.css'],
  imports: [FormsModule] // Import if not in module
})
export class MyFormComponent {
  user = { name: '', email: '' };

  onSubmit() {
    if (this.myForm.valid) {
      // Access form data using this.myForm.value or this.user object
      console.log("Form submitted!", this.user);
    }
  }
}

4. Add validation (optional):

Use built-in validators like required, minlength, and email directly in your HTML using attributes like required, minlength, and pattern. Alternatively, you can define custom validators in your component and reference them in the template.

Additional Tips:

  • Use form groups and form arrays for complex forms with nested structures.

  • Leverage ngModelChange event for dynamic updates and feedback.

  • Explore directives like ngClass and ngStyle for conditional styling based on form state.

Remember, template-driven forms offer a good starting point for basic forms. For more complex scenarios or granular control, consider exploring reactive forms in Angular.



No comments:

Post a Comment

Note: only a member of this blog may post a comment.