AngularJS Forms

 

 

 

 

 

 Using Forms in AngularJS

 

e-trainings-forms-demo

Forms are used to accept data from the user. In angular, you can create 2 types of forms
    1. Template driven forms.
    2. Reactive forms.
 

In this blog, you are going to learn How to create AngularJS Template driven forms.

So First of all

 

1. Create an App

       C:\> ng new forms-app
      
C:\> cd  forms-app

2. Create a component test

       C:\>forms-app>  ng generate component test

 

 

3. Configure forms in app.module.ts file.

import { Component, NgModule, OnInit } from '@angular/core';

import { BrowserModule } from '@angular/platform-browser';
import {FormsModule, NgForm} from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';

import { AppComponent } from './app.component';
import { TestComponent } from './test/test.component';

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

4. Create a simple form to display user entered text.

    a. Add the below code in test.component.html file as follows −

 

<p>test works!</p>

<form #userData="ngForm" (ngSubmit)="onClickSubmit(userData.value)"> 
  Enter Some Text: <input type="text" name="userData" placeholder="Type Here" ngModel> 
   <br/> 
   <br/> 
   <input type="submit" value="submit"> 
</form>
 
 
    b. Use ngModel attribute in input text field.

    c. Create onClickSubmit() method inside test.component.ts file.
 
Now, the code looks as follows 
 
 
import { Component, OnInit } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser';
import {FormsModule, NgForm} from '@angular/forms';


@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {

  constructor() { }

  ngOnInit(): void {  }
 
  onClickSubmit(result:any) {
      alert("You have entered : " + result.userData); 
   }

} 

 5. Open app.component.html and change the content as specified below −

<app-test></<app-test>



Finally, start your application (if not done already) using the below command −

C:\> C:\>forms-app> ng serve

 
  
Output:
 
coding-zon-forms-demo

 

 

 

 

 

 

 

 

Comments

Popular posts from this blog

Using javascript pass form variables to iframe src

Creating a new PDF by Merging PDF documents using TCPDF

Import excel file into mysql in PHP