Wednesday 30 August 2017

Routing in Angular 2 or 4


The Angular router is an external, optional Angular NgModule called RouterModule. The router is a combination of multiple provided services (RouterModule), multiple directives (RouterOutlet, RouterLink, RouterLinkActive), and a configuration (Routes). You'll configure the routes first.

<base href>
Open index.html and ensure there is a <base href="..."> element (or a script that dynamically sets this element) at the top of the <head> section.

<router-outlet>
you can add a <router-outlet> element at the end of the template. RouterOutlet is one of the directives provided by the RouterModule. The router displays each component immediately below the <router-outlet> as users navigate through the app





1. src/index.html

<head>

  <base href="/">


2. app.routing.ts 

import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
/*All Router Component import here*/
import { LoginComponent } from '../Components/Dashboard/login.component';

const appRoutes: Routes = [
{   path: '/login',  component: LoginComponent },
{   path: '',  redirectTo: '/home',  pathMatch: 'full'},
{   path: 'detail/:id',  component: DetailComponent},
];
export const masterrouting: ModuleWithProviders = RouterModule.forRoot(appRoutes);

==============================================================

3. app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HttpModule } from '@angular/http';
import { masterrouting } from '../app.routing';

import {MasterComponent} from '../app.master.component';
import { LoginComponent } from '../app.login.component';

@NgModule({
  declarations: [MasterComponent,LoginComponent],
  imports: [BrowserModule,masterrouting,HttpModule,CommonModule],
  providers: [],
  bootstrap: [MasterComponent]
})

export class MasterModule { }
==============================================================


4.app.MasterComponent

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  template: '<router-outlet></router-outlet>',
})

export class MasterComponent {}



5. app.LoginComponent

import { Component,OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { ActivatedRoute, ParamMap } from '@angular/router';

import { Location }   from '@angular/common';
import 'rxjs/add/operator/switchMap';

@Component({
  templateUrl: '../Login.component.html',
})
export class LoginComponent implements OnInit {        
constructor(public _router:Router, private _location: Location){}

ngOnInit(): void {
  this.route.paramMap
    .switchMap((params: ParamMap) => this.heroService.getHero(+params.get('id')))
    .subscribe(hero => this.hero = hero);

}

change( id):number
{
this._router.navigate(['/detail', id]);


}
"Note:=> users can click one of the two links in the AppComponent or click the browser's back button. Now add a third option, a goBack() method that navigates backward one step in the browser's history stack using the Location service you injected previously."

goBack(): void {
  this._location.back();

}
===============================================================

6. login.compoment.html

<div>
<!-- -Css->
<style>
          .active{color:blue;font-weight:bold;}
</style>
<ui>
     <li> <a routerLink="/home" routerLinkActive="active"> </li>
     <li> <a routerLink="/detail/"+Id+"" routerLinkActive="active"> </li>
     <li> <button  (click)="change(id)"/>Submit </li>
     <li> <button  (click)="goBack()"/>Submit </li>

</ui>
<div>
<a *ngFor="let hero of heroes"  [routerLink]="['/detail', hero.id]"  class="col-1-4">
</div>

</div>

Friday 25 August 2017

Routing , master page, login form and validate in Angular JS 4

Angular JS All file related to stare project=>

1. main.ts  file
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { MasterModule} from './app/Modules/master.module'
import { environment } from './environments/environment';

if (environment.production) {
enableProdMode();
}

platformBrowserDynamic().bootstrapModule(MasterModule);

2. master.module.ts  file
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';
import { HttpModule } from '@angular/http';
import { masterrouting } from '../Routing/master.routing';

import { MasterheaderComponent } from '../Components/Header/master.header';
import {MasterComponent} from '../Components/Dashboard/master.component';
import { LoginComponent } from '../Components/Dashboard/login.component';

@NgModule({
declarations: [MasterComponent,LoginComponent,MasterheaderComponent,MasterfooterComponent,HomeComponent,EventComponent,AddforumComponent,EmpdashboardComponent,
EmpheaderComponent,EmpleftComponent],
imports: [BrowserModule,masterrouting,HttpModule,CommonModule,FormsModule,ReactiveFormsModule],
providers: [],
bootstrap: [MasterComponent]
})
export class MasterModule { }

3. master.component.ts file
import { Component } from '@angular/core';

@Component({
selector: 'app-root',
template: '<router-outlet></router-outlet>',
})
export class MasterComponent {
}

4. master.routing.ts
import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
/*All Router Component import here*/
import { LoginComponent } from '../Components/Dashboard/login.component';
import { HomeComponent } from '../Components/Dashboard/home.component';

const appRoutes: Routes = [
{
path: '',
component: LoginComponent
},
];

export const masterrouting: ModuleWithProviders = RouterModule.forRoot(appRoutes);

5. login.component.ts file
import { Component,OnInit } from '@angular/core';
import { loginServices} from '../../Services/Dashboard/login.services';
import { Router } from '@angular/router';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { logininfo } from '../../Services/Dashboard/login.interface';

@Component({
templateUrl: '../../UI/Dashboard/Login.component.html',
styleUrls: ['../../Content/Css/master.css'],
providers: [loginServices,logininfo]
})
export class LoginComponent implements OnInit {
login:boolean=true;
forgot:boolean=false;
active = true;
uservalid = false;
Invaliduser: string;

constructor(public _lservices:loginServices, public _router:Router, public data:logininfo,private fb: FormBuilder){}

ngOnInit(): void {
this.buildForm();
}


LoginForm: FormGroup;
buildForm(): void {
this.LoginForm = this.fb.group({
'EmailAddress': [this.data.EmailAddress, [
Validators.required,
Validators.minLength(4),
Validators.maxLength(24)]
],
'Password': [this.data.Password, Validators.required]
});

this.LoginForm.valueChanges
.subscribe(data => this.onValueChanged(data));

this.onValueChanged(); // (re)set validation messages now
}


onValueChanged(data?: any) {
this.uservalid = false;
if (!this.LoginForm) { return; }
const form = this.LoginForm;
for (const field in this.formErrors) {
// clear previous error message (if any)
this.formErrors[field] = '';
const control = form.get(field);
if (control && control.dirty && !control.valid) {
const messages = this.validationMessages[field];
for (const key in control.errors) {
this.formErrors[field] += messages[key] + ' ';
}
}
}
}

formErrors = {
'EmailAddress': '',
'Password': ''
};

validationMessages = {
'EmailAddress': {
'required': 'Name is required.',
'minlength': 'Name must be at least 4 characters long.',
'maxlength': 'Name cannot be more than 24 characters long.'
},
'Password': {
'required': 'Password is required.'
}
};


emplogin()
{
this._lservices.login(this.data).subscribe(res => this.result(res), res => this.errorlogin(res));
}

result(info: any) {
if (info != null) {
alert(info.EmpId);
localStorage.setItem("ID", info.EmpId);
localStorage.setItem("Name", info.Name);
this._router.navigateByUrl('/dashboard');
}
else {
alert('Invalid User details');
}
}
errorlogin(res: any) {
console.log(res);
};


resetpass()
{
this.login=false;
this.forgot=true;
}
Login()
{
this.forgot=false;
this.login=true;
}
}

6. login.services.ts file
import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map';
import { Observable } from "rxjs/Rx";
import { Router } from '@angular/router';
import { logininfo } from '../../Services/Dashboard/login.interface';
import {userinfo,Actype} from './userinfo';

@Injectable()

export class loginServices{

constructor(private _http: Http, private _router : Router) { }

login(obj:logininfo) {
let _headers = new Headers({ 'Content-Type': 'application/json' });
return this._http.post('http://localhost:53656/api/Login/checklogin', obj, { headers: _headers }).map(res => res.json());

//return this._http.get('http://localhost:53656/api/Login/checklogin?EmailAddress=' + EmailAddress + '&Password=' + Password + '').map(res => res.json());
}
_url:string;
info:string;
constructor(private http: Http){ }
/*Get All Account Type start here*/
getAccounttype() {
return this.http.get('http://localhost:64592/api/Laboratory/GetAccounttype?type=1').map(res=>res.json()); }

/*End*/

/*Insert User information start here*/
adduser(data:userinfo) {
var headers = new Headers();
headers.append('Content-Type','application/json; charset=utf-8');
return this.http.post('http://localhost:64592/api/Laboratory/Savedata',data,{headers: headers}).map(res => res.json()); }
/*End*/

/*User Login start here*/
login(data:logininfo)
{
var headers =new Headers();
headers.append('Content-Type','application/json,charset=utf-8')
return this.http.get('http://localhost:64592/api/Laboratory/Loginuser?email='+data.EmailAddress+'&pass='+data.Password+'').map(res=>res.json());
}
/*End*/

/*Get all User Information start here*/
getuser(){
return this.http.get('http://localhost:64592/api/Laboratory/GetInfo').map(res=>res.json()); }
/*End*/
}

7. login.component.HTML file

<style>
body {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 14px;
line-height: 1.42857143;
color: #333;
background-color: #fff;
}
</style>
<div id="wrapwrap">
<master-header> </master-header>
<main>
<div class="oe_website_login_container" style="margin-top: 10%; margin-bottom: 22.5%;">
<form class="oe_login_form" [formGroup]="LoginForm" *ngIf="active" (ngSubmit)="emplogin()">
<div *ngIf="login">
<div class="form-group field-login">
<label for="login" class="control-label">User</label>
<input name="login" id="login" class="form-control" formControlName="EmailAddress" [(ngModel)]="data.EmailAddress" autofocus="autofocus" type="text">
<div *ngIf="formErrors.EmailAddress" class="error"> {{ formErrors.EmailAddress }}</div>
</div>
<div class="form-group field-password">
<label for="password" class="control-label">Password</label>
<input name="Password" id="Password" class="form-control" formControlName="Password" [(ngModel)]="data.Password" type="password">
<div *ngIf="formErrors.EmailAddress" class="error"> {{ formErrors.Password }}</div>
</div>
<div class="clearfix oe_login_buttons">
<a (click)="resetpass()" class="btn btn-link pull-right">Reset Password</a>
<button type="submit" class="btn btn-primary" value="login" [disabled]="!LoginForm.valid">Login</button>
<!--<button type="submit" (click)="emplogin()" class="btn btn-primary">Log in</button>-->
</div>
</div>
<div *ngIf="forgot">
<div class="form-group field-login">
<label for="login" class="control-label">Your Email</label>
<input name="login" id="login" class="form-control" autofocus="autofocus" required="required" type="text">
</div>
<div class="clearfix oe_login_buttons">
<a class="btn btn-link pull-right" (click)="Login()">Back to Login</a>
<button type="submit" class="btn btn-primary pull-left">Reset password</button>
</div>
</div>
</form>
</div>
</main>
</div>


8.master.header.ts
import { Component } from '@angular/core';

@Component({
selector: 'master-header',
templateUrl: '../../UI/Header/master.header.html',
styleUrls: ['../../Content/Css/master.css']

})
export class MasterheaderComponent {
}


9.
<div id="wrapwrap">
<header>
<div class="navbar navbar-default navbar-static-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-top-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a href="/" class="navbar-brand logo">
<img src="../assets/Img/logo.png" alt="Logo of Virtual Employee Pvt. Ltd." title="Virtual Employee Pvt. Ltd.">
</a>
</div>
<div class="collapse navbar-collapse navbar-top-collapse">
<ul class="nav navbar-nav navbar-right" id="top_menu">
<li>
<a routerLink="/home" routerLinkActive="active">
<span>Home</span>
</a>
</li>
<li>
<a href="/event">
<span>Events</span>
</a>
</li>
<li class="dropdown ">
<a class="dropdown-toggle" data-toggle="dropdown" href="/addforum">
<span>Forum</span> <span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li>
<a href="/home/forum">
<span>View</span>
</a>
</li>
<li>
<a href="/home/forum/addnew">
<span>Add New</span>
</a>
</li>
</ul>
</li>
<li class="divider"></li>
<li>
<a href="/">
<b>Sign in</b>
</a>
</li>
</ul>
</div>
<marquee> <div><span><span style="font-size: 17px;color:red;">TDS Declaration has been started now, you can submit declaration and check your tax in TDS Calculator.</span><span><span style="text-align: justify;"><span style="font-size: 17px; line-height: 26.9841289520264px;color:#35ce35;">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Many Many Happy Returns Of The Day To&nbsp;</span><span style="font-size: 17px; line-height: 26.9841289520264px; color:#ff00ee;">Mridu Singh, </span><span style="font-size: 17px; line-height: 26.9841289520264px; color:#003fff;"> Abhijeet Sadashiv Khot, Mithilesh Kumar, </span><span style="font-size: 17px; line-height: 26.9841289520264px;color:#35ce35;">&nbsp;from VIRTUAL EMPLOYEE Family</span></span></span><span><span style="font-size: 17px;">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Form 16 has been uploaded ! If TDS declaration given then you can find the form inside&nbsp;</span><span style="color: rgb(255, 0, 0); font-family: &quot;Lucida Grande&quot;, Helvetica, Verdana, Arial, sans-serif; font-size: 17px;">declaration by year </span><span style="font-size: 17px;">&nbsp; under TAX in &nbsp;</span><span style="color: rgb(255, 0, 0); font-family: &quot;Lucida Grande&quot;, Helvetica, Verdana, Arial, sans-serif; font-size: 17px;">human resource</span><span style="font-size: 17px;">&nbsp;tab else you can download it from </span><span style="color: rgb(255, 0, 0); font-family: &quot;Lucida Grande&quot;, Helvetica, Verdana, Arial, sans-serif; font-size: 17px;"> tax declaration tab in </span><span style="font-size: 17px;">your dashboard inside </span><span style="color: rgb(255, 0, 0); font-family: &quot;Lucida Grande&quot;, Helvetica, Verdana, Arial, sans-serif; font-size: 17px;">employee tab in human resource tab.</span></span></span></div></marquee>
</div>
</div>
</header>
</div>






.





All command related angular 2 or 4

All command related angular 2 or 4:

node JS latest version=>  https://nodejs.org/en/download/current/
Angular js 2 or 4 CLI=>  https://cli.angular.io/
Angular js 2 or 4 API=>  https://angular.io/api





CMD Description
1 npm install –g @angular/cli
1. For install all dependences of angularJS 2 or 4 in your System.


2 ng new my-project-name
1. Default applications are created in a directory of the same name, with an
Initialized Angular application.
2. Scaffold and maintain Angular applications.
3 cd my-project-name 1. Go same location where you create project.
4 ng serve
or



ng serve --host 0.0.0.0 --port 4201
1. Ng serve builds the application and starts a web server.
2. Build using Ahead of Time compilation (AOT).
3. Default port value: 4200
4. Enable and define the file watching poll time period (milliseconds).
5. Start web pack dev server.
6. Change Port number of application.
5 ng generate [name] 1. Ng generates the specified blueprint (module, component, service, class, interface, directive, enum, guard, pipe, service).
6 ng –g controller [name] 1. This is also working same as above g stand for generate.
7 ng test
1. Compiles the application into an output directory.
2. Tests will execute after a build is executed via Karma, and it will automatically watch your files for changes
8 ng e2e 1. serves the application and runs end-to-end tests
9 ng build 1. Compiles the application into an output directory.
10 *ngFor
<li *ngFor="let user of list | async as users; index as i; first as isFirst"></li>
1. index: number: The index of the current item in the iterable.
2. first: boolean: True when the item is the first item in the iterable.
3. last: boolean: True when the item is the last item in the iterable.
4. even: boolean: True when the item has an even index in the iterable.
5. odd: boolean: True when the item has an odd index in the iterable.
11 *ngIf
ngIF=> <div *ngIf=”true”></div>
ngIF and else=> <div *ngIf=”true; else elseBlock ”></div>
12 [ngPlural]
Use as a switch statement.
<some-element [ngPlural]="value">
<ng-template ngPluralCase="=0">...</ng-template>
<ng-template ngPluralCase="other">...</ng-template>
</some-element>
13 [ngStyle] <H [ngStyle]="{'font-style': styleExp}">...</h>
14 [ngSwitch]
1. <div [ngSwitch]="expression"> <span ngSwitchCase="matchExp ">...</span></div>
2. <span *ngSwitchDefault>...</span>
15 async
1. The async pipe subscribes to an Observable or Promise and returns the latest value it has emitted.
2. <div><code>observable|async</code>: Time: {{ time | async }}</div>


16 date                  
<p>Today is {{today | date}}</p>
<p>Or if you prefer, {{today | date:'fullDate'}}</p>
<p>The time is {{today | date:'jmZ'}}</p>
17 JSON <pre>{{object | json}}</pre>
18 lowercase <p>In lowercase: <pre>'{{value | lowercase}}'</pre>


uppercase <p>In lowercase: <pre>'{{value | uppercase}}'</pre>
19 currency
"number_expression | currency[:currencyCode[:symbolDisplay[:digitInfo]]]"
<p>A: {{a | currency:'USD':false}}</p>
<p>B: {{b | currency:'USD':true:'4.2-2'}}</p>
20 number <p>e (3.1-5): {{e | number:'3.1-5'}}</p>
21 percent
<p>A: {{a | percent}}</p>
<p>B: {{b | percent:'4.3-5'}}</p>
22 slice
<li *ngFor="let i of collection | slice:1:3">{{i}}</li>
<li string | slice:1:3">{{i}}</li>
23 titlecasepipe <li string | titlecasepipe "></li>


24 .  ng build    =>     using for build application and bundling all type script.

25.   npm uninstall -g angular-cli  => uninstall angular .

26.   npm uninstall --save-dev angular-cli => uninstall but save your development work.

27. update Angular CLI to a new version, you must update both the global package and your project's local package.

      A. Global package:
                            npm uninstall -g @angular/cli
                            npm cache clean
                            npm install -g @angular/cli@latest

      B. Local project package:
                          rm -rf node_modules dist # use rmdir /S/Q node_modules dist in Windows Command                           Prompt; use rm -r -fo node_modules,dist in Windows PowerShell
                          npm install --save-dev @angular/cli@latest
                          npm install

28. ng serve --host 0.0.0.0 --port 4201  => Change Port number of application.

29. npm install -g nodemon =>    Nodemon is a utility that will monitor for any changes in your                                                                 source and automatically restart your server