Simple first program in Angular


 First Program

Hey guys, in this post we are going to see how to create a basic angular application or we can say the first program in angular. Let’s do it step by step.
[At the bottom you will get the link to download the project]
For basic installation and all setup please refer our previous post here

At Very first create a new project
Command: ng new ProjectName




Then open your project into visual studio code by giving the path of root directory
Now create the component
Command: ng generate component ComponentName
Or
Command: ng g c ComponentName



As soon as you run the command, your component gets generated. And as you know, the component contains four files.
In the image, we have created a component named firstpage, so we get four files for the same component

firstPage.component.html
-               this file contains HTML code that’s why we call it view
firstPage.component.ts
-               this file contains business logic, all data manipulation goes here
firstPage.component.css
-               As all we know this is to apply styling to our code
firstPage.component.spec.ts
-               Here you don’t have to do anything right now, this is for debugging purpose 

Create one more component So we can have two pages in our application
Command: ng g c secondPage
We will get
secondPage.component.html
secondPage.component.ts
secondPage.component.css
secondPage.component.spec.ts

Now you are ready with components
Here we are simply going to design two simple pages of login and register

firstPage.component.html

<div class="container">
  <form #frm="ngForm" id="frm"><br><br>
    <div class="row">
      <div class="col-lg-4"></div>
      <div class="col-lg-6">
        <h3>Login</h3>
        <table>
          <thead>
            <th>
              Login Name
            </th>
            <th>
              <input class="form-control" type="text" [(ngModel)]="user.userName"                          name="userName" required>
            </th>
          </thead>
          <tbody>
            <tr>
              <th>
                Password
              </th>
              <td><input class="form-control" type="password"                                                 [(ngModel)]="user.password" name="password"></td>
            </tr>
            <tr>
              <td>
              </td>
              <td>
                <button class="btn btn-primary">Login</button>&nbsp;
                <button class="btn btn-light" (click)="registerMe();">Register                               Me</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </form>
</div>

Here in the above page, we have created one basic HTML page which is to accept user credential

firstPage.component.ts

import { Component, OnInit, HostListener, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { user } from '../user/user';

@Component({
  selector: 'app-first-page',
  templateUrl: './first-page.component.html',
  styleUrls: ['./first-page.component.css']
})

export class FirstPageComponent implements OnInit {
 
  private user = new user();
  constructor(private router: Router) { }

  ngOnInit() {
    console.log("user : " + user.name);
  }

  registerMe() {
    this.router.navigate(['/secondpage']);
  }

}



Above is the components typescript file to do the business logic, in the above file we have just added code to go from this page to secondPage,
 This.router.navigate([‘/secondpage’]) will navigate us to the second page, with the help of URL we have provided to this method, which will be mapped by router file “app-routing.module.ts” (we will see this file later) to the secondpage and will go to that component.
(registerMe() function is called on register button click)

secondPage.component.html

<div class="row">
  <div class="col-lg-4"></div>
  <div class="col-lg-6">
    <form action="" #frm="ngForm">
      <h3>Registration</h3>
      <table>
        <tr>
          <td>User name</td>
          <td><input [(ngModel)]="user.userName" class="form-control" type="text"                          name="userName"></td>
        </tr>
        <tr>
          <td>password</td>
          <td><input [(ngModel)]="user.password" class="form-control"                                      type="password" name="password"></td>
        </tr>
        <tr>
          <td>confirm password</td>
          <td><input class="form-control" type="password" name="password"></td>
        </tr>
        <tr>
          <td>email</td>
          <td><input [(ngModel)]="user.email" class="form-control" type="text"                            name="email"></td>
        </tr>
        <tr>
          <td>contact No</td>
          <td><input [(ngModel)]="user.contactNo" class="form-control" type="text"                         name="contactNo"></td>
        </tr>
        <tr>
          <td>address</td>
          <td><input [(ngModel)]="user.address" class="form-control" type="text"                           name="address"></td>
        </tr>
        <tr>
          <td></td>
          <td><button class="btn btn-light"                                                             (click)="gotoLogin()">Cancel</button>&nbsp;
               <button class="btn btn-primary" (click)="saveData()">save</button>              </td>
        </tr>
      </table>
    </form>
  </div>
</div>

This HTML file contains HTML code for user registration

secondPage.component.ts

import { Component, OnInit, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { user } from '../user/user';

@Component({
  selector: 'app-second-page',
  templateUrl: './second-page.component.html',
  styleUrls: ['./second-page.component.css']
})
export class SecondPageComponent implements OnInit {
 
  private user = new user();

  constructor(private router: Router) { }

  ngOnInit() {
  }

  gotoLogin() {
    this.router.navigate(['/firstpage']);
  }
 
  saveData(){
    alert('User data saved successfully');
    this.router.navigate(['/firstpage']);
  }
}


Yes, you have both pages. Now the important thing is, do you have routing in your project? (If you followed our basic setup in the previous post, you are on right track) if yes, that’s cool. if not please add routing file to your project so we can go from one page to another.
Command: ng generate module app-routing –flat –module=app
Or shortened
Command: ng g m app-routing –flat
And add routing URL/path for our both pages/components so we can go to that page.

app-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { FirstPageComponent } from './first-page/first-page.component';
import { SecondPageComponent } from './second-page/second-page.component';

const routes: Routes = [
  { path: 'firstpage', component: FirstPageComponent },
  { path: 'secondpage', component: SecondPageComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})

export class AppRoutingModule { }

Bingo…, your simple application is ready. In this application you have two components and one routing file to go from one page/component to other.
This application does not connect to or does not call any web service to get data from the server. This is pure front-end content you can do here any manipulation with existing content.
To do call web services or to hit server we need service, which we will see in our next post, and for your convenience, we will continue same example.

Comments