Environment Setup:
Step 1: Install the Angular CLI
npm install -g @angular/cli
Step 2: Create a workspace and initial application
ng new my-app
Step 3: Run the application
Go to the workspace folder (my-app
).
Launch the server by using the CLI command ng serve
, with the --open
option.
cd my-app
ng serve –open
Create Component through cli.
ng g c component-name
or
ng generate
component component-name
Create Component skip test files
C:\angular\sampleapp> ng g c footer --skip-tests
CREATE src/app/footer/footer.component.html (21 bytes)
CREATE src/app/footer/footer.component.ts (276 bytes)
CREATE src/app/footer/footer.component.scss (0 bytes)
UPDATE src/app/app.module.ts (557 bytes)
Create Service
ng g s servicename
or
ng generate service servicename
or Ex(service folder and userservice => ng g s service/user)
ng g s folder/servicename
Create Interceptor
ng g interceptor interceptorname
Router-Outlet
here HomeComponent is an default parent component remaining components will load within this router-outlet
const routes: Routes = [
{path:'',component:HomeComponent,
children: [
{path:'header',component:HeaderComponent},
{path:'userinfo',component:UserinfoComponent},
{path:'footer',component:FooterComponent}
]},
];
html : header will shown all child components.
<p>home works!</p>
<app-header></app-header>
<router-outlet></router-outlet>
create Model Class
export class Ingredient
{
public name:string;
public amount:number;
constructor(name:string,amount:number)
{
this.name=name;
this.amount=amount;
}
}
Or
export class Ingredient1
{
constructor(public name:string,public amount:number)
{
}
}
Both are same.
Debuging Tool:
add extension chrome and it will helpful for debug.
Input Onchange
event:
Html
<input type="text" class="formcontrol" (input)="onTextChange($event)">
<p>{{onTxtChangeExample}}</p>
Ts
public onTxtChangeExample='';
onTextChange(event:Event)
{
this.onTxtChangeExample=(<HTMLInputElement> event.target).value;
(<HTMLInputElement> event.target).value=(<HTMLInputElement> event.target).value+"1";
}
NgModel video 34:
Ng Module declaration should be in app.module.ts file
Import section:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import{FormsModule}from '@angular/forms';
@NgModule({
//here we need to
include what are all the components required
declarations: [
AppComponent,
HomeComponent,
CockpitComponent,
SeverElementComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
then in your
component html be like:
<label>Server Name</label>
<input type="text" class="formcontrol" [(ngModel)]="newServerName">
<label>Server content</label>
<input type="text" class="formcontrol" [(ngModel)]="newServerContent">
ngFor example:
ts
export class HomeComponent implements OnInit {
public newServerName:string;
newServerContent:string;
serverElements=[{type:'Server',name:'Test Serve',content:'Test'}]
constructor() { }
ngOnInit(): void {
}
}
html
<div *ngFor="let Server of serverElements">
<div *ngIf="Server.type==='Server'" style="color: red;">{{Server.type}} {{Server.name}} {{Server.content}}</div>
<div *ngIf="Server.type!='Server'" style="color: green;">{{Server.type}} {{Server.name}} {{Server.content}}</div>
Or
Init list of array objects:
import {ServerDetail}from '../shared//ServerDetail.model';
serverElements:ServerDetail[];
ngOnInit(): void {
this.serverElements=[];
}
Parent to child comunication using
@Input() –(video 65)
Parent:
Ts
import { Component, OnInit } from '@angular/core';
import { ServerDetail } from '../shared/ServerDetail.model';
@Component({
selector: 'app-parent-server',
templateUrl: './parent-server.component.html',
styleUrls: ['./parent-server.component.scss']
})
export class ParentServerComponent implements OnInit {
// serverElements:ServerDetail[];
serverElements=[{type:'Server',name:'Arul',content:'Test'},{type:'Blueprint',name:'Arul-1',content:'Test'}]
constructor() { }
ngOnInit(): void {
//this.serverElements=[];
}
}
Html(passing each serverElement to element in
child component which receive @input() element
<small>parent</small>
<div class="container">
<app-cockpit></app-cockpit>
</div>
<div class="container">
<b>Server Details</b>
<app-sever-element *ngFor="let serverElement of serverElements" [element]="serverElement"></app-sever-element>
</div>
Child:
Ts(same signature
of parent)
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-sever-element',
templateUrl: './sever-element.component.html',
styleUrls: ['./sever-element.component.scss']
})
export class SeverElementComponent implements OnInit {
// @Input() element:{type:string,name:string,content:string}
@Input() element:{type:string,name:string,content:string}
constructor() { }
ngOnInit(): void {
}
}
Html: (no iteraion
here , iterations containing parent)
<div>
<div *ngIf="element.type==='Server'" style="color: red;">{{element.type}} {{element.name}} {{element.content}}</div>
<div *ngIf="element.type!='Server'" style="color: green;">{{element.type}} {{element.name}} {{element.content}}</div>
</div>
Or we can pass
parm in @input (‘paramname’)
Parent html
<app-sever-element
*ngFor="let serverElement of serverElements" [srvElement]="serverElement"
></app-sever-element>
Child ts
@Input('srvElement') element:{type:string,name:string,content:string}
Child to parent using Output
Emitters:
Parent html :
<small>parent</small>
<div class="container">
<app-cockpit
(serverCreated)="OnServerAdded($event)"
(blueprintCreated)="onBluePrintAdded($event)"
(serverCreated1)="OnServerAdded($event)"
(blueprintCreated1)="onBluePrintAdded($event)"
></app-cockpit>
</div>
Parent ts
OnServerAdded(serverData:{serverName:string,serverContent:string})
{
this.serverElements.push({type:'Server',name:serverData.serverName,content:serverData.serverContent});
}
onBluePrintAdded(serverData:{serverName:string,serverContent:string})
{
this.serverElements.push({type:'Blueprint',name:serverData.serverName,content:serverData.serverContent});
}
Child ts:
import { Component, OnInit,EventEmitter, Output } from '@angular/core';
@Output() serverCreated=
new EventEmitter<{serverName:string,serverContent:string}>();
@Output() blueprintCreated=
new EventEmitter<{serverName:string,serverContent:string}>();
@Output() serverCreated1=
new EventEmitter<{serverName:string,serverContent:string}>();
@Output() blueprintCreated1=
new EventEmitter<{serverName:string,serverContent:string}>();
constructor() { }
ngOnInit(): void {
}
OnAddServer()
{
this.serverCreated.emit({serverName:this.newServerName,serverContent:this.newServerContent});
this.serverCreated1.emit({serverName:this.newServerName,serverContent:this.newServerContent});
//this.serverElements.push({type:'Server',name:this.newServerName,content:this.newServerContent});
}
onAddBluePrint()
{
this.blueprintCreated.emit({serverName:this.newServerName,serverContent:this.newServerContent});
this.blueprintCreated1.emit({serverName:this.newServerName,serverContent:this.newServerContent});
//this.serverElements.push({type:'Blueprint',name:this.newServerName,content:this.newServerContent});
}
Routing:
App.module.ts
import {Routes, RouterModule} from '@angular/router';
const appRoutes:Routes=[
{path:'',component:HomeComponent},
{path:'singlepage',component:HomeComponent},
{path:'parentserver',component:ParentServerComponent},
{path:'cockpit',component:CockpitComponent},
];
@NgModule({
declarations: [
AppComponent,
HomeComponent,
CockpitComponent,
SeverElementComponent,
ParentServerComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
RouterModule.forRoot(appRoutes)
],
providers: [],
bootstrap: [AppComponent]
})
Html
<div class="row">
<ul>
<li><a href="/">Home</a> </li>
<li><a href="/singlepage">Single page</a> </li>
<li><a href="/parentserver">Parent server</a></li>
<!--without page refresh-->
<li><a routerLink='/'>Home</a> </li>
<li><a routerLink="/singlepage">Single page</a> </li>
<!--For provide multiple sub components then we can use property binding
['/component','subcompenent','anothersub component']-->
<li><a [routerLink]="['/parentserver']">Parent server</a></li>
</ul>
</div>
<div>
<!--Here load the component based on routing-->
<router-outlet></router-outlet>
</div>
Allow 2 digit Decimal value from 0.01 to 100 validation:
HTML:
<input type="text" maxlength="5"
(focusout)="onTextboxFocusOutDecimalPercentageValidate($event)"
(input)="onTextboxChangeDecimalPercentageValidate($event)">
TS:
onTextboxChangeDecimalPercentageValidate(event: Event) {
var inputData = (<HTMLInputElement>event.target).value;
//replace more than one dot
var extractedFte = inputData.replace(/[^0-9.]/g, '').replace('.', 'x')
.replace(/\./g, '').replace('x', '.');
//Extract Decimal Values
extractedFte = extractedFte.replace(/^(\d+.?\d{0,2})\d*$/, "$1");
//Reasign to same control
(<HTMLInputElement>event.target).value = extractedFte;
if (extractedFte != '' && Number(extractedFte) >= 100) {
(<HTMLInputElement>event.target).value = '100'; extractedFte = '100';
}
// if (Number(extractedFte) == 0) {
// (<HTMLInputElement>event.target).value = ''; extractedFte = '';
// }
}
onTextboxFocusOutDecimalPercentageValidate(event: Event) {
var inputData = (<HTMLInputElement>event.target).value;
//replace more than one dot
var extractedFte = inputData.replace(/[^0-9.]/g, '').replace('.', 'x')
.replace(/\./g, '').replace('x', '.');
//Extract Decimal Values
extractedFte = extractedFte.replace(/^(\d+.?\d{0,2})\d*$/, "$1");
//Reasign to same control
(<HTMLInputElement>event.target).value = extractedFte;
if (extractedFte != '' && Number(extractedFte) >= 100) {
(<HTMLInputElement>event.target).value = '100'; extractedFte = '100';
}
if (Number(extractedFte) == 0) {
(<HTMLInputElement>event.target).value = ''; extractedFte = '';
}
}