- Angular 4 – Examples
- Angular 4 – CLI
- Angular 4 – Materials
- Angular 4 – Animations
- Angular 4 – Forms
- Angular 4 – Http Service
- Angular 4 – Services
- Angular 4 – Routing
- Angular 4 – Pipes
- Angular 4 – Directives
- Angular 4 – Templates
- Angular 4 – Event Binding
- Angular 4 – Data Binding
- Angular 4 – Module
- Angular 4 – Components
- Angular 4 – Project Setup
- Angular 4 – Environment Setup
- Angular 4 – Overview
- Angular 4 - Home
Angular 4 Useful Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Angular 4 - Examples
In this chapter, we will discuss a few examples related to Angular 4.
To begin with, we have created an example which shows a login form with input as username and password. Upon entering the correct values, it will enter inside and show another form wherein, you can enter the customer details. In addition, we have created four components - header, footer, userlogin and mainpage.
The components are created using the following command −
ng g component header
C: gexamplesaexamples>ng g component header instalpng component create srcappheaderheader.component.css create srcappheaderheader.component.html create srcappheaderheader.component.spec.ts create srcappheaderheader.component.ts update srcappapp.module.ts
ng g component footer
C: gexamplesaexamples>ng g component footer instalpng component create srcappfooterfooter.component.css create srcappfooterfooter.component.html create srcappfooterfooter.component.spec.ts create srcappfooterfooter.component.ts update srcappapp.module.ts
ng g component userlogin
C: gexamplesaexamples>ng g component userlogin instalpng component create srcappuserloginuserlogin.component.css create srcappuserloginuserlogin.component.html create srcappuserloginuserlogin.component.spec.ts create srcappuserloginuserlogin.component.ts update srcappapp.module.ts
ng g component mainpage
C: gexamplesaexamples>ng g component mainpage instalpng component create srcappmainpagemainpage.component.css create srcappmainpagemainpage.component.html create srcappmainpagemainpage.component.spec.ts create srcappmainpagemainpage.component.ts update srcappapp.module.ts
In the app.module.ts, the parent module has all the components added when created. The file looks as follows −
import { BrowserModule } from @angular/platform-browser ; import { NgModule } from @angular/core ; import { ReactiveFormsModule } from @angular/forms ; import { RouterModule, Routes} froms @angular/router ; import { BrowserAnimationsModule } from @angular/platform-browser/animations ; import {MdTableModule} from @angular/material ; import {HttpModule} from "@angular/http"; import {MdInputModule} from @angular/material ; import { AppComponent } from ./app.component ; import { HeaderComponent } from ./header/header.component ; import { FooterComponent } from ./footer/footer.component ; import { UserloginComponent } from ./userlogin/userlogin.component ; import { MainpageComponent } from ./mainpage/mainpage.component ; const appRoutes: Routes = [ { path: , component: UserloginComponent }, { path: app-mainpage , component: MainpageComponent } ]; @NgModule({ declarations: [ AppComponent, HeaderComponent, FooterComponent, UserloginComponent, MainpageComponent ], imports: [ BrowserModule, ReactiveFormsModule, RouterModule.forRoot(appRoutes), BrowserAnimationsModule, HttpModule, MdTableModule, MdInputModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
The components created above are added −
import { HeaderComponent } from ./header/header.component ; import { FooterComponent } from ./footer/footer.component ; import { UserloginComponent } from ./userlogin/userlogin.component ; import { MainpageComponent } from ./mainpage/mainpage.component ;
The components are added in the declarations too −
declarations: [ AppComponent, HeaderComponent, FooterComponent, UserloginComponent, MainpageComponent ],
In the parent app.component.html, we have added the main structure of the file that will be seen by the user.
<span class="mainpage"> <app-header></app-header> <router-outlet></router-outlet> <app-footer></app-footer> </span>
We have created a span and added <app-header></app-header>, <router-outlet></router-outlet> and <app-footer></app-footer>.
The <router-outlet></router-outlet> is used for navigation between one page to another. Here, the pages are login-form and once it is successful it will redirect to the mainpage, i.e., the customer form.
To get the login-form first and later get the mainpage.component.html, the changes are done in app.module.ts as shown below −
import { BrowserModule } from @angular/platform-browser ; import { NgModule } from @angular/core ; import { ReactiveFormsModule } from @angular/forms ; import { RouterModule, Routes} from @angular/router ; import { BrowserAnimationsModule } from @angular/platform-browser/animations ; import {MdTableModule} from @angular/material ; import {HttpModule} from "@angular/http"; import {MdInputModule} from @angular/material ; import { AppComponent } from ./app.component ; import { HeaderComponent } from ./header/header.component ; import { FooterComponent } from ./footer/footer.component ; import { UserloginComponent } from ./userlogin/userlogin.component ; import { MainpageComponent } from ./mainpage/mainpage.component ; const appRoutes: Routes = [ { path: , component: UserloginComponent }, { path: app-mainpage , component: MainpageComponent } ]; @NgModule({ declarations: [ AppComponent, HeaderComponent, FooterComponent, UserloginComponent, MainpageComponent ], imports: [ BrowserModule, ReactiveFormsModule, RouterModule.forRoot(appRoutes), BrowserAnimationsModule, HttpModule, MdTableModule, MdInputModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
We have imported RouterModule and Routes from @anuglar/router. In imports, the RouterModules takes appRoutes as the param which is defined above as −
const appRoutes: Routes = [ { path: , component: UserloginComponent }, { path: app-mainpage , component: MainpageComponent } ];
Routes take the array of components and by default the userloginComponent is called.
In userlogin.component.ts, we have imported the router and navigated to mainpage.component.html based on the condition as shown below −
import { Component, OnInit } from @angular/core ; import { FormGroup, FormControl, Vapdators} from @angular/forms ; import { Router} from @angular/router ; @Component({ selector: app-userlogin , templateUrl: ./userlogin.component.html , styleUrls: [ ./userlogin.component.css ] }) export class UserloginComponent implements OnInit { formdata; constructor(private router: Router) { } ngOnInit() { this.formdata = new FormGroup({ uname: new FormControl("", Vapdators.compose([ Vapdators.required, Vapdators.minLength(6) ])), passwd: new FormControl("", this.passwordvapdation) }); } passwordvapdation(formcontrol) { if (formcontrol.value.length < 5) { return {"passwd" : true}; } } onCpckSubmit(data) { console.log(data.uname); if (data.uname=="systemadmin" && data.passwd=="admin123") { alert("Login Successful"); this.router.navigate([ app-mainpage ]) } else { alert("Invapd Login"); return false; } } }
Following is the .ts file for app.component.ts. Only the default details are present in it.
import { Component } from @angular/core ; @Component({ selector: app-root , templateUrl: ./app.component.html , styleUrls: [ ./app.component.css ] }) export class AppComponent {title = app ;}
Let us now display the details of each of the components files. To start with, we will first take the header component. For the new component, four files are created header.component.ts, header.component.html, header.component.css, and header.component.spec.ts.
header.component.ts
import { Component, OnInit } from @angular/core ; @Component({ selector: app-header , templateUrl: ./header.component.html , styleUrls: [ ./header.component.css ] }) export class HeaderComponent implements OnInit { constructor() { } ngOnInit() {} }
header.component.html
<span> <hr /> </span>
We have not added any css. This makes the header.component.css file empty. Also, the header.compoent.spec.ts file is empty as the test cases are not considered here.
For the header, we will draw a horizontal pne. A logo or any other detail can be added to make the header look more creative.
Let us now consider creating a footer component.
For the footer component, footer.component.ts, footer.component.html, footer.component.spec.ts and footer.component.css files are created.
footer.component.ts
import { Component, OnInit } from @angular/core ; @Component({ selector: app-footer , templateUrl: ./footer.component.html , styleUrls: [ ./footer.component.css ] }) export class FooterComponent implements OnInit { constructor() { } ngOnInit() { } }
footer.component.html
<hr/>
As we have not added any css, the footer.component.css file is empty. Also, the footer.compoent.spec.ts file is empty as the test cases are not considered here.
For the footer, we will just draw a horizontal pne as shown in the .html file.
Let us now see how the userlogin component works. The following files for userlogin component created are userlogin.component.css, userlogin.component.html, userlogin.component.ts, and userlogin.component.spec.ts.
The details of the files are as follows −
userlogin.component.html
<span class="form_container"> <form [formGroup]="formdata" (ngSubmit) = "onCpckSubmit(formdata.value)" > <header>Login</header> <label>Username <span>*</span></label> <input type="text" name="uname" formControlName="uname"/> <span class="help">At least 6 character</span> <label>Password <span>*</span></label> <input type="password" class="fortextbox" name="passwd" formControlName="passwd"/> <span class="help">Use upper and lowercase lettes as well</span> <button [disabled]="!formdata.vapd" value="Login">Login</button> </form> </span>
Here, we have created form with two input controls Username and Password. This is a model driven form approach and the details of the same are explained in Chapter 14 - Forms.
We consider the username and password mandatory, hence the vapdation for the same is added in the ts. Upon cpcking the submit button, the control is passed to the onCpckSubmit, which is defined in the ts file.
userlogin.component.ts
import { Component, OnInit } from @angular/core ; import { FormGroup, FormControl, Vapdators} from @angular/forms ; import { Router} from @angular/router ; @Component({ selector: app-userlogin , templateUrl: ./userlogin.component.html , styleUrls: [ ./userlogin.component.css ] }) export class UserloginComponent implements OnInit { formdata; constructor(private router: Router) { } ngOnInit() { this.formdata = new FormGroup({ uname: new FormControl("", Vapdators.compose([ Vapdators.required, Vapdators.minLength(6) ])), passwd: new FormControl("", this.passwordvapdation) }); } passwordvapdation(formcontrol) { if (formcontrol.value.length < 5) { return {"passwd" : true}; } } onCpckSubmit(data) { console.log(data.uname); if (data.uname == "systemadmin" && data.passwd == "admin123") { alert("Login Successful"); this.router.navigate([ app-mainpage ]) } } }
For the formcontrol and vapdation, the modules are imported as shown below
import { FormGroup, FormControl, Vapdators} from @angular/forms ;
We need a router to navigate to a different component when the user and password are correct. For this, the router is imported as shown below −
import { Router} from @angular/router ;
In ngOnInit, the vapdation for the form is done. We need the username to be more than six characters and the field is mandatory. The same condition apppes to password too.
Upon cpcking submit, we can check if the username is systemadmin and the password is admin123. If yes, a dialog box appears that shows Login Successful and the router navigates to the app-mainpage, which is the selector of the mainpage component.
There is css added for the form in userlogin.component.css file −
.form_container{ margin : 0 auto; width:600px; } form { background: white; width: 500px; box-shadow: 0px 0px 20px rgba(0, 0, 0, 0.7); font-family: lato; position: relative; color: #333; border-radius: 10px; } form header { background: #FF3838; padding: 30px 20px; color: white; font-size: 1.2em; font-weight: 600; border-radius: 10px 10px 0 0; } form label { margin-left: 20px; display: inpne-block; margin-top: 30px; margin-bottom: 5px; position: relative; } form label span { color: #FF3838; font-size: 2em; position: absolute; left: 2.3em; top: -10px; } form input { display: block; width: 50%; margin-left: 20px; padding: 5px 20px; font-size: 1em; border-radius: 3px; outpne: none; border: 1px sopd #ccc; } form .help { margin-left: 20px; font-size: 0.8em; color: #777; } form button { position: relative; margin-top: 30px; margin-bottom: 30px; left: 50%; transform: translate(-50%, 0); font-family: inherit; color: white; background: #FF3838; outpne: none; border: none; padding: 5px 15px; font-size: 1.3em; font-weight: 400; border-radius: 3px; box-shadow: 0px 0px 10px rgba(51, 51, 51, 0.4); cursor: pointer; transition: all 0.15s ease-in-out; } form button:hover { background: #ff5252; }
The userlogin.component.spec.ts file is empty as there no test cases right now.
Let us now discuss how the mainpage component works. The files created for mainpage component are mainpage.component.ts, mainpage.component.html, mainpage.component.css, and mainpage.component.spect.ts.
mainpage.component.ts
import { Component, OnInit, ViewChild} from @angular/core ; import { FormGroup, FormControl, Vapdators} from @angular/forms ; import {Http, Response, Headers, RequestOptions } from "@angular/http"; import rxjs/add/operator/map ; @Component({ selector: app-mainpage , templateUrl: ./mainpage.component.html , styleUrls: [ ./mainpage.component.css ] }) export class MainpageComponent implements OnInit { formdata; cutomerdata; constructor(private http: Http) { } stateCtrl: FormControl; ngOnInit() { this.formdata = new FormGroup({ fname: new FormControl("", Vapdators.compose([ Vapdators.required, Vapdators.minLength(3) ])), lname: new FormControl("", Vapdators.compose([ Vapdators.required, Vapdators.minLength(3) ])), address:new FormControl(""), phoneno:new FormControl("") }); } onCpckSubmit(data) { document.getElementById("custtable").style.display=""; this.cutomerdata = []; for (var prop in data) { this.cutomerdata.push(data[prop]); } console.log(this.cutomerdata); } }
We have created a customer form with firstname, lastname , address and phone number. The vapdation of the same is done with the ngOnInit function. Upon cpcking submit, the control comes to the function onCpckSubmit. Here, the table which is used to display the entered details is made visible.
The customerdata is converted from json to array so that we can use the same in ngFor on the table, which is done in the .html file as shown below.
mainpage.component.html
<span class="form_container"> <form [formGroup]="formdata" (ngSubmit) = "onCpckSubmit(formdata.value)" > <header>Customer Details</header> <label>FirstName <span>*</span></label> <input type="text" name="fname" formControlName="fname"/> <label>LastName <span>*</span></label> <input type="text" name="lname" formControlName="lname"/> <label>Address <span></span></label> <input type="text" name="address" formControlName="address"/> <label>Phone No <span></span></label> <input type="text" name="phoneno" formControlName="phoneno"/> <button [disabled]="!formdata.vapd" value="Submit">Submit</button> </form> </span> <br/> <span id="custtable" style="display:none;margin:0 auto;"> <table> <tr> <td>FirstName</td> <td>LastName</td> <td>Address</td> <td>Phone No</td> </tr> <tr> <td *ngFor="let data of cutomerdata"> <h5>{{data}}</h5> </td> </tr> </table> </span>
Here, the first span has the customer details and the second span has the table, which will show the entered details. The display of the userlogin and the customer details is as shown below. This is the page with login form and header and footer.
Once you enter the details, the display is as shown below
Upon cpcking submit, a dialog box appears which shows Login Successful.
If the details are invapd, a dialog box appears which shows Invapd Login as shown below −
If the login is successful, it will proceed to the next form of Customer Details as shown below −
Once the details are entered and submitted, a dialog box appears which shows the Customer Details are added as shown in the screenshot below −
When we cpck OK in the above screenshot, the details will appear as shown in the screenshot below −
Advertisements