Angular 13 – Basic Forms ,2024

In this chapter, we will discuss Template Driven From in angular 13. In this example, I have used app component files like ts and HTML.

In Basic form or Template Driven From most of the work is done in the HTML template using the model-driven form.

Let’s start using the template-driven form in angular 13. we will create simple user details form add name, email & form input text. then we will use the following steps.

Step 1). we need to import to FormsModule from @angular/core in app.module.ts as follows – and also declare in imports[] array

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { IndexComponent } from './post/index/index.component';
import { ViewComponent } from './post/view/view.component';
import { CreateComponent } from './post/create/create.component';
import { AddDetailsComponent } from './add-details/add-details.component';
import { FormsModule } from '@angular/forms';

@NgModule({
  declarations: [
    AppComponent,
    IndexComponent,
    ViewComponent,
    CreateComponent,
    AddDetailsComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Step 2). Let’s create the form in app.components.html

<h1>{{title}}</h1>

<h3>Basic form  in angular</h3>

<form #userData="ngForm" (ngSubmit)="onClickSubmit(userData.value)">
    <input type="text" name="name" placeholder="Full Name" ngModel />
    <br/><br/>
    <input type="text" name="email" placeholder="Email Id" ngModel />
    <br/><br/>
    <input type="text" name="phone" placeholder="Phone Number" ngModel />
    <br/><br/>

    <input type="submit" name="submit" />
    <br/><br/>

    <b>Output : </b><br>
<p>
    Name:{{userDetails.name}}<br>
    Email:{{userDetails.email}}<br>
    Phone:{{userDetails.phone}}<br>
</p>


</form>

in the template-driven form we are using to get data from the form input field with the name attribute and add the ngModel attribute.

Step 3). In the app.component.ts file create onClickSubmit() method to pass data from the component to the HTML template.

import { Component } from '@angular/core';
import { NgForm } from '@angular/forms';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Piyush Maurya';



userDetails:any = {};
  onClickSubmit(data:any){
       console.log(data);
       this.userDetails   =  data;
  }
}

Output:

Discover more from STRUGGLER KING.COM

Subscribe now to keep reading and get access to the full archive.

Continue Reading