angular logo

Angular: You first form

Before continuing with this article please go through the article Getting Started with AngularJS

Creating Your First Form

Now open your “testapp” project in any code editor like SublimeText, VisualStudio Code or you can work on individual files with a notepad.

Goto the folder testapp->src->app and open app.component.html. Replace the existing template with the template below.

 <h1>
  {{title}}
</h1>
<div>
    <p>
    Name: <input type="text" [(ngModel)]="person.name"/>
    </p>
    <p>
    Address: <input type="text" [(ngModel)]="person.address"/>
    </p>
    <p>
    City: <input type="text" [(ngModel)]="person.city"/>
    </p>
    <button (click)="Save()">Save</button>
    <button (click)="Clear()">Clear</button>
</div>
<div>
    <br/>
    Name: {{person1.name}} <br/>
    Address:{{person1.address}}<br/>
    City:{{person1.city}}
</div>

In the same folder open app.component.ts and replace the existing code with the code below.

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Test Form';

  person = {
      name:"",
      address:"",
      city:""
  };
  person1={};

  Save(){
    this.person1=this.person;
    this.person={
        name:"",
        address:"",
        city:""
    };
  }

  Clear(){
      this.person={
        name:"",
        address:"",
        city:""
    };
    this.person1={};
  }
}

Now open the command/terminal window and run the application from “testapp” folder using the command “ng server –open”. Your application should look like this

angular first form

You can enter the three fields and click on Save to display in the bottom or click on Clear to clear the text fields.

In the above code [[ngModel]] attribute is used for two way binding. An empty person object with the fields name, address and city is created in the TypeScript file.

Once you enter the text in the form, that data is automatically binded to the person object. There are two methods Clear and Save in the class, you can see that Clear resets the person object and the temporary person1 object.

The Save method copies the person object into person1 object to display in the bottom section. You can see in the template that the bottom section is binded with person1 object.

<-previous: Getting Started with AngularJS