Angular Merged
Angular Merged
#angular
Table of Contents
About 1
Remarks 2
Versions 3
Examples 5
Prerequisites: 6
Prerequisites: 8
Examples 13
Examples 15
Chapter 4: Forms 16
Examples 16
Reactive Forms 16
app.module.ts 16
app.component.ts 16
app.component.html 17
validators.ts 18
Template Driven Forms 18
Template - signup.component.html 18
Component - signup.component.ts 19
Model - signup-request.model.ts 19
Chapter 5: Pipes 21
Introduction 21
Examples 21
Custom Pipes 21
Chapter 6: Routing 24
Examples 24
Basic Routing 25
Examples 28
Basic Request 28
Introduction 29
Remarks 29
Examples 29
Send data from parent component to child component via data binding using @Input 30
Sending data asynchronous from parent to child using Observable and Subject 32
Credits 35
About
You can share this PDF with anyone you feel could benefit from it, downloaded the latest version
from: angular
It is an unofficial and free Angular ebook created for educational purposes. All the content is
extracted from Stack Overflow Documentation, which is written by many hardworking individuals at
Stack Overflow. It is neither affiliated with Stack Overflow nor official Angular.
The content is released under Creative Commons BY-SA, and the list of contributors to each
chapter are provided in the credits section at the end of this book. Images may be copyright of
their respective owners unless otherwise specified. All trademarks and registered trademarks are
the property of their respective company owners.
Use the content presented in this book at your own risk; it is not guaranteed to be correct nor
accurate, please send your feedback and corrections to info@zzzprojects.com
https://riptutorial.com/ 1
Chapter 1: Getting started with Angular
Remarks
Angular (commonly referred to as "Angular 2+" or "Angular 2") is a TypeScript-based open-
source front-end web framework led by the Angular Team at Google and by a community of
individuals and corporations to address all of the parts of the developer's workflow while building
complex web applications. Angular is a complete rewrite from the same team that built AngularJS.
¹
The framework consists of several libraries, some of them core (@angular/core for example) and
some optional (@angular/animations).
You write Angular applications by composing HTML templates with Angularized markup, writing
component classes to manage those templates, adding application logic in services, and boxing
components and services in modules.
Then you launch the app by bootstrapping the root module. Angular takes over, presenting your
application content in a browser and responding to user interactions according to the instructions
you've provided.
Arguably, the most fundamental part of developing Angular applications are the components. A
component is the combination of an HTML template and a component class that controls a portion
of the screen. Here is an example of a component that displays a simple string:
src/app/app.component.ts
@Component({
selector: 'my-app',
template: `<h1>Hello {{name}}</h1>`
})
export class AppComponent {
name = 'Angular';
}
Every component begins with a @Component decorator function that takes a metadata object. The
metadata object describes how the HTML template and component class work together.
The selector property tells Angular to display the component inside a custom <my-app> tag in the
index.html file.
The template property defines a message inside a <h1> header. The message starts with "Hello"
https://riptutorial.com/ 2
and ends with {{name}}, which is an Angular interpolation binding expression. At runtime, Angular
replaces {{name}} with the value of the component's name property. Interpolation binding is one of
many Angular features you'll discover in this documentation. In the example, change the
component class's name property from 'Angular' to 'World' and see what happens.
This example is written in TypeScript, a superset of JavaScript. Angular uses TypeScript because
its types make it easy to support developer productivity with tooling. Additionally, almost all
support is for TypeScript and so using plain JavaScript to write your application will be difficult
. Writing Angular code in JavaScript is possible, however; this guide explains how.
Versions
4.3.2 2017-07-26
5.0.0-beta.0 2017-07-19
4.3.1 2017-07-19
4.3.0 2017-07-14
4.2.6 2017-07-08
4.2.5 2017-06-09
4.2.4 2017-06-21
4.2.3 2017-06-16
4.2.2 2017-06-12
4.2.1 2017-06-09
4.2.0 2017-06-08
4.2.0-rc.2 2017-06-01
4.2.0-rc.1 2017-05-26
4.2.0-rc.0 2017-05-19
4.1.3 2017-05-17
4.1.2 2017-05-10
https://riptutorial.com/ 3
Version Release Date
4.1.1 2017-05-04
4.1.0 2017-04-26
4.1.0-rc.0 2017-04-21
4.0.3 2017-04-21
4.0.2 2017-04-11
4.0.1 2017-03-29
4.0.0 2017-03-23
4.0.0-rc.6 2017-03-23
4.0.0-rc.5 2017-03-17
4.0.0-rc.4 2017-03-17
2.4.10 2017-03-17
4.0.0-rc.3 2017-03-10
2.4.9 2017-03-02
4.0.0-rc.2 2017-03-02
4.0.0-rc.1 2017-02-24
2.4.8 2017-02-18
2.4.7 2017-02-09
2.4.6 2017-02-03
2.4.5 2017-01-25
2.4.4 2017-01-19
2.4.3 2017-01-11
2.4.2 2017-01-06
2.4.1 2016-12-21
2.4.0 2016-12-20
2.3.1 2016-12-15
https://riptutorial.com/ 4
Version Release Date
2.3.0 2016-12-07
2.3.0-rc.0 2016-11-30
2.2.4 2016-11-30
2.2.3 2016-11-23
2.2.2 2016-11-22
2.2.1 2016-11-17
2.2.0 2016-11-14
2.2.0-rc.0 2016-11-02
2.1.2 2016-10-27
2.1.1 2016-10-20
2.1.0 2016-10-12
2.1.0-rc.0 2016-10-05
2.0.2 2016-10-05
2.0.1 2016-09-23
2.0.0 2016-09-14
2.0.0-rc.7 2016-09-13
2.0.0-rc.6 2016-08-31
2.0.0-rc.5 2016-08-09
2.0.0-rc.4 2016-06-30
2.0.0-rc.3 2016-06-21
2.0.0-rc.2 2016-06-15
2.0.0-rc.1 2016-05-03
2.0.0-rc.0 2016-05-02
Examples
https://riptutorial.com/ 5
Installation of Angular using angular-cli
This example is a quick setup of Angular and how to generate a quick example project.
Prerequisites:
• Node.js 6.9.0 or greater.
• npm v3 or greater or yarn.
• Typings v1 or greater.
The first command installs the typings library globally (and adds the typings executable to PATH).
The second installs @angular/cli globally, adding the executable ng to PATH.
ng new PROJECT_NAME
cd PROJECT_NAME
ng serve
That is it, you now have a simple example project made with Angular. You can now navigate to the
link displayed in terminal and see what it is running.
ng init
This will add the necessary scaffolding to your project. The files will be created in the current
directory so be sure to run this in an empty directory.
ng serve
If the server started successfully it should display an address at which the server is running.
Usually is this:
http://localhost:4200
Out of the box this local development server is hooked up with Hot Module Reloading, so any
changes to the html, typescript, or css, will trigger the browser to be automatically reloaded (but
can be disabled if desired).
# The command below will generate a component in the folder you are currently at
ng generate component my-generated-component
# Using the alias (same outcome as above)
ng g component my-generated-component
# You can add --flat if you don't want to create new folder for a component
ng g component my-generated-component --flat
# You can add --spec false if you don't want a test file to be generated (my-generated-
component.spec.ts)
ng g component my-generated-component --spec false
https://riptutorial.com/ 7
Scaffold Type Usage
You can also replace the type name by its first letter. For example:
Building/Bundling
When you are all finished building your Angular web app and you would like to install it on a web
server like Apache Tomcat, all you need to do is run the build command either with or without the
production flag set. Production will minifiy the code and optimize for a production setting.
ng build
or
ng build --prod
Then look in the projects root directory for a /dist folder, which contains the build.
If you'd like the benefits of a smaller production bundle, you can also use Ahead-of-Time template
compilation, which removes the template compiler from the final build:
Unit Testing
Angular provides in-built unit testing, and every item created by angular-cli generates a basic unit
test, that can be expended. The unit tests are written using jasmine, and executed through Karma.
In order to start testing execute the following command:
ng test
This command will execute all the tests in the project, and will re-execute them every time a
source file changes, whether it is a test or code from the application.
Prerequisites:
Setting up the Development Environment
https://riptutorial.com/ 8
• Install Node.js and npm if they are not already on your machine.
Verify that you are running at least node 6.9.x and npm 3.x.x by running node -v and npm -v
in a terminal/console window. Older versions produce errors, but newer versions are fine.
ng new my-app
Here the ng is for Angular. We get a file structure something like this.
https://riptutorial.com/ 9
There are lots of files. We need not worry about all of them now.
ng serve
We may use a flag -open( or simply -o) which will automatically open our browser on
http://localhost:4200/
ng serve --open
https://riptutorial.com/ 10
The CLI created the default Angular component for us. This is the root component and it is named
app-root. One can find it in ./src/app/app.component.ts.
Open the component file and change the title property from Welcome to app!! to Hello World. The
browser reloads automatically with the revised title.
Original HTML
Modified HTML
https://riptutorial.com/ 11
Notice that the value of title from the ./src/app/app.component.ts will be displayed. The browser
reloads automatically when the changes are done. It looks something like this.
https://riptutorial.com/ 12
Chapter 2: Event Emitter
Examples
Catching the event
Create a service-
@Component({
selector: 'obs-comp',
template: `obs component, item: {{item}}`
})
export class ObservingComponent {
item: number = 0;
subscription: any;
constructor(private navService:NavService) {}
ngOnInit() {
this.subscription = this.navService.getNavChangeEmitter()
.subscribe(item => this.selectedNavItem(item));
}
selectedNavItem(item: number) {
this.item = item;
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
@Component({
selector: 'my-nav',
template:`
<div class="nav-item" (click)="selectedNavItem(1)">nav 1 (click me)</div>
<div class="nav-item" (click)="selectedNavItem(2)">nav 2 (click me)</div>
`,
})
export class Navigation {
item = 1;
constructor(private navService:NavService) {}
https://riptutorial.com/ 13
selectedNavItem(item: number) {
console.log('selected nav item ' + item);
this.navService.emitNavChangeEvent(item);
}
}
https://riptutorial.com/ 14
Chapter 3: For Loop
Examples
NgFor - Markup For Loop
The NgFor directive instantiates a template once per item from an iterable. The context for each
instantiated template inherits from the outer context with the given loop variable set to the current
item from the iterable.
To customize the default tracking algorithm, NgFor supports trackBy option. trackBy takes a
function which has two arguments: index and item. If trackBy is given, Angular tracks changes by
the return value of the function.
Additional Options: NgFor provides several exported values that can be aliased to local
variables:
• index will be set to the current loop iteration for each template context.
• first will be set to a boolean value indicating whether the item is the first one in the iteration.
• last will be set to a boolean value indicating whether the item is the last one in the iteration.
• even will be set to a boolean value indicating whether this item has an even index.
• odd will be set to a boolean value indicating whether this item has an odd index.
https://riptutorial.com/ 15
Chapter 4: Forms
Examples
Reactive Forms
app.module.ts
Add these into your app.module.ts file to use reactive forms
@NgModule({
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule,
],
declarations: [ AppComponent ]
providers: [],
bootstrap: [ AppComponent ]
})
export class AppModule {}
app.component.ts
@Component({
selector: 'app',
template
})
export class AppComponent implements OnInit {
addForm: FormGroup;
ngOnInit() {
this.addForm = this.formBuilder.group({
username: ['', Validators.required],
email: ['', Validators.required],
role: ['', Validators.required],
password: ['', Validators.required],
password2: ['', Validators.required]
}, { validator: matchingPasswords('password', 'password2') });
https://riptutorial.com/ 16
};
addUser() {
if (this.addForm.valid) {
var adduser = {
username: this.addForm.controls['username'].value,
email: this.addForm.controls['email'].value,
password: this.addForm.controls['password'].value,
profile: {
role: this.addForm.controls['role'].value,
name: this.addForm.controls['username'].value,
email: this.addForm.controls['email'].value
}
};
console.log(adduser);// adduser var contains all our form values. store it where
you want
this.addForm.reset();// this will reset our form values to null
}
}
app.component.html
<div>
<form [formGroup]="addForm">
<input
type="text"
placeholder="Enter username"
formControlName="username" />
<input
type="text"
placeholder="Enter Email Address"
formControlName="email"/>
<input
type="password"
placeholder="Enter Password"
formControlName="password" />
<input
type="password"
placeholder="Confirm Password"
name="password2"
formControlName="password2" />
https://riptutorial.com/ 17
</select>
<br/>
<br/>
<button type="submit" (click)="addUser()">
<span>
<i class="fa fa-user-plus" aria-hidden="true"></i>
</span>
Add User
</button>
</form>
</div>
validators.ts
Template - signup.component.html
<div class="title">
Sign Up
</div>
<div class="input-field">
<label for="username">username</label>
<input
type="text"
pattern="\w{4,20}"
name="username"
required="required"
[(ngModel)]="signUpRequest.username" />
</div>
<div class="input-field">
<label for="email">email</label>
<input
type="email"
pattern="^\S+@\S+$"
name="email"
required="required"
https://riptutorial.com/ 18
[(ngModel)]="signUpRequest.email" />
</div>
<div class="input-field">
<label for="password">password</label>
<input
type="password"
pattern=".{6,30}"
required="required"
name="password"
[(ngModel)]="signUpRequest.password" />
</div>
<div class="status">
{{ status }}
</div>
</form>
Component - signup.component.ts
@Component({
selector: 'app-signup',
templateUrl: './signup.component.html',
styleUrls: ['./signup.component.css']
})
export class SignupComponent {
status: string;
signUpRequest: SignUpRequest;
constructor() {
this.signUpRequest = new SignUpRequest();
}
onSubmit(value, valid) {
this.status = `User ${this.signUpRequest.username} has successfully signed up`;
}
Model - signup-request.model.ts
constructor(
public username: string="",
public email: string="",
https://riptutorial.com/ 19
public password: string=""
) {}
@NgModule({
declarations: [
AppComponent,
SignupComponent
],
imports: [
BrowserModule,
FormsModule
],
bootstrap: [AppComponent]
})
export class AppModule { }
<app-signup></app-signup>
https://riptutorial.com/ 20
Chapter 5: Pipes
Introduction
Pipes are very similar to filters in AngularJS in that they both help to transform the data into a
specified format.The pipe character | is used to apply pipes in Angular.
Examples
Custom Pipes
my.pipe.ts
@Pipe({name: 'myPipe'})
export class MyPipe implements PipeTransform {
my.component.ts
@Component({
selector: 'my-component',
template: `{{ value | myPipe }}`
})
export class MyComponent {
public value:any;
my.module.ts
@NgModule({
imports: [
BrowserModule,
],
https://riptutorial.com/ 21
declarations: [
MyComponent,
MyPipe
],
})
export class MyModule { }
Having different pipes is a very common case, where each pipe does a different thing. Adding
each pipe to each component may become a repetitive code.
It is possible to bundle all frequently used pipes in one Module and import that new module in any
component needs the pipes.
breaklines.ts
uppercase.ts
pipes.module.ts
@NgModule({
declarations: [
BreakLine,
Uppercase
],
imports: [
https://riptutorial.com/ 22
],
exports: [
BreakLine,
Uppercase
]
,
})
export class PipesModule {}
my.component.ts
@Component({
selector: 'my-component',
template: `{{ value | upper | br}}`
})
export class MyComponent {
my.module.ts
@NgModule({
imports: [
BrowserModule,
PipesModule,
],
declarations: [
MyComponent,
],
})
https://riptutorial.com/ 23
Chapter 6: Routing
Examples
Routing with children
I found this to be the way to properly nest children routes inside the app.routing.ts or
app.module.ts file (depending on your preference). This approach works when using either
WebPack or SystemJS.
The example below shows routes for home, home/counter, and home/counter/fetch-data. The first
and last routes being examples of redirects. Finally at the end of the example is a proper way to
export the Route to be imported in a separate file. For ex. app.module.ts
To further explain, Angular requires that you have a pathless route in the children array that
includes the parent component, to represent the parent route. It's a little confusing but if you think
about a blank URL for a child route, it would essentially equal the same URL as the parent route.
https://riptutorial.com/ 24
path: "**",
redirectTo: "home"
}
];
@NgModule({
imports: [
RouterModule.forRoot(appRoutes)
],
exports: [
RouterModule
]
})
export class AppRoutingModule { }
Basic Routing
Router enables navigation from one view to another based on user interactions with the
application.
<base href='/'>
as the first child under your head tag in your index.html file. This element states that your app
folder is the application root. Angular would then know how to organize your links.
1. Check if you are pointing to the correct/latest routing dependencies in package.json (using
the latest version of Angular) and that you already did an npm install -
"dependencies": {
"@angular/router": "^4.2.5"
}
interface Route {
path?: string;
pathMatch?: string;
component?: Type<any>;
}
3. In a routing file (routes/app.routing.ts), import all the components which you need to
configure for different routing paths. Empty path means that view is loaded by default. ":" in
the path indicates dynamic parameter passed to the loaded component.
https://riptutorial.com/ 25
import { BarDetailComponent } from '../components/bar-detail.component';
import { DashboardComponent } from '../components/dashboard.component';
import { LoginComponent } from '../components/login.component';
import { SignupComponent } from '../components/signup.component';
@Component({
selector: 'demo-app',
template: `
<div>
<router-outlet></router-outlet>
</div>
`
})
export class AppComponent {}
6. Link the other routes. By default, RouterOutlet will load the component for which empty path
is specified in the Routes. RouterLink directive is used with html anchor tag to load the
components attached to routes. RouterLink generates the href attribute which is used to
generate links. For example:
@Component({
selector: 'demo-app',
template: `
<a [routerLink]="['/login']">Login</a>
<a [routerLink]="['/signup']">Signup</a>
<a [routerLink]="['/dashboard']">Dashboard</a>
<div>
<router-outlet></router-outlet>
https://riptutorial.com/ 26
</div>
`
})
export class AnotherComponent { }
Now, we are good with routing to static paths. RouterLink supports dynamic path too by passing
extra parameters along with the path.
@Component({
selector: 'demo-app',
template: `
<ul>
<li *ngFor="let bar of bars | async">
<a [routerLink]="['/bars', bar.id]">
{{bar.name}}
</a>
</li>
</ul>
<div>
<router-outlet></router-outlet>
</div>
`
})
export class SecondComponent { }
RouterLinktakes an array where the first parameter is the path for routing and subsequent
elements are for the dynamic routing parameters.
https://riptutorial.com/ 27
Chapter 7: RXJS and Observables
Examples
Wait for multiple requests
One common scenario is to wait for a number of requests to finish before continuing. This can be
accomplished using the forkJoin method.
In the following example, forkJoin is used to call two methods that return Observables. The callback
specified in the .subscribe method will be called when both Observables complete. The
parameters supplied by .subscribe match the order given in the call to .forkJoin. In this case, first
posts then tags.
loadData() : void {
Observable.forkJoin(
this.blogApi.getPosts(),
this.blogApi.getTags()
).subscribe((([posts, tags]: [Post[], Tag[]]) => {
this.posts = posts;
this.tags = tags;
}));
}
Basic Request
The following example demonstrates a simple HTTP GET request. http.get() returns an
Observable which has the method subscribe. This one appends the returned data to the posts array.
var posts = []
getPosts(http: Http): {
this.http.get(`https://jsonplaceholder.typicode.com/posts`)
.subscribe(response => {
posts.push(response.json());
});
}
https://riptutorial.com/ 28
Chapter 8: Sharing data among components
Introduction
The objective of this topic is to create simple examples of several ways data can be shared
between components via data binding and shared service.
Remarks
There are always many of ways of accomplishing one task in programming. Please feel free to edit
current examples or add some of your own.
Examples
Sending data from parent component to child via shared service
service.ts:
@Injectable()
export class AppState {
parent.component.ts:
@Component({
selector: 'parent-example',
templateUrl: 'parent.component.html',
})
export class ParentComponent {
mylistFromParent = [];
add() {
this.appState.mylist.push({"itemName":"Something"});
}
parent.component.html:
https://riptutorial.com/ 29
<p> Parent </p>
<button (click)="add()">Add</button>
<div>
<child-component></child-component>
</div>
child.component.ts:
@Component({
selector: 'child-component',
template: `
<h3>Child powered by shared service</h3>
{{mylist | json}}
`,
})
export class ChildComponent {
mylist: any;
Send data from parent component to child component via data binding using
@Input
parent.component.ts:
@Component({
selector: 'parent-example',
templateUrl: 'parent.component.html',
})
add() {
this.mylistFromParent.push({"itemName":"Something"});
}
parent.component.html:
<div>
<child-component [mylistFromParent]="mylistFromParent"></child-component>
</div>
https://riptutorial.com/ 30
child.component.ts:
@Component({
selector: 'child-component',
template: `
<h3>Child powered by parent</h3>
{{mylistFromParent | json}}
`,
})
event-emitter.component.ts
@Component({
selector: 'event-emitting-child-component',
template: `<div *ngFor="let item of data">
<div (click)="select(item)">
{{item.id}} = {{ item.name}}
</div>
</div>
`
})
data;
@Output()
selected: EventEmitter<string> = new EventEmitter<string>();
ngOnInit(){
this.data = [ { "id": 1, "name": "Guy Fawkes", "rate": 25 },
{ "id": 2, "name": "Jeremy Corbyn", "rate": 20 },
{ "id": 3, "name": "Jamie James", "rate": 12 },
{ "id": 4, "name": "Phillip Wilson", "rate": 13 },
{ "id": 5, "name": "Andrew Wilson", "rate": 30 },
{ "id": 6, "name": "Adrian Bowles", "rate": 21 },
{ "id": 7, "name": "Martha Paul", "rate": 19 },
{ "id": 8, "name": "Lydia James", "rate": 14 },
{ "id": 9, "name": "Amy Pond", "rate": 22 },
{ "id": 10, "name": "Anthony Wade", "rate": 22 } ]
}
select(item) {
this.selected.emit(item);
https://riptutorial.com/ 31
event-receiver.component.ts:
@Component({
selector: 'event-receiver-parent-component',
template: `<event-emitting-child-component (selected)="itemSelected($event)">
</event-emitting-child-component>
<p *ngIf="val">Value selected</p>
<p style="background: skyblue">{{ val | json}}</p>`
})
itemSelected(e){
this.val = e;
}
}
shared.service.ts:
import 'rxjs/add/operator/toPromise';
@Injectable()
export class AppState {
public setData(value) {
this.dataStringSource.next(value);
}
fetchFilterFields() {
console.log(this.apiUrl);
return this.http.get(this.apiUrl)
.delay(2000)
.toPromise()
https://riptutorial.com/ 32
.then(response => response.json().data)
.catch(this.handleError);
}
parent.component.ts:
@Component({
selector: 'parent-component',
template: `
<h2> Parent </h2>
<h4>{{promiseMarker}}</h4>
<div>
<child-component></child-component>
</div>
`
})
export class ParentComponent implements OnInit {
promiseMarker = "";
ngOnInit(){
this.getData();
}
getData(): void {
this.appState
.fetchFilterFields()
.then(data => {
// console.log(data)
this.appState.setData(data);
this.promiseMarker = "Promise has sent Data!";
});
}
child.component.ts:
@Component({
selector: 'child-component',
template: `
https://riptutorial.com/ 33
<h3>Child powered by shared service</h3>
{{fields | json}}
`,
})
export class ChildComponent {
fields: any;
this.appState.dataString$.subscribe(
data => {
// console.log("Subs to child" + data);
this.fields = data;
});
https://riptutorial.com/ 34
Credits
S.
Chapters Contributors
No
RXJS and
7 aholtry
Observables
https://riptutorial.com/ 35
ANGULARJS
CHEAT SHEET
AngularJS is an extensible and exciting new JavaScript MVC framework developed by Google for
building well-designed, structured and interactive single-page applications (SPA). It lays strong
emphasis on Testing and Development best practices such as templating and declarative bi-directional
data binding.
This cheat sheet co-authored by Ravi Kiran and Suprotim Agarwal, aims at providing a quick reference to
the most commonly used features in AngularJS. It will also make you quickly productive with Angular.
This article is from the Free DNC Magazine for .Net and JavaScript developers. Subscribe to
this magazine for free (using only your email address) and download all the editions.
BEGINNER
www.dotnetcurry.com/magazine 01
04 Module: svc.addCity = function(city){
cities.push(city);
};
Create a module named myModule1 that depends on
myModule2 and myModule2: svc.getCities = function(){
angular.module(“myModule1”,[“myModule2”, return cities;
“myModule2”]) }
});
Get reference to the module myModule1
angular.module(“myModule1”) The members added to instance of the service are visible to the
outside world. Others are private to the service. Services are
05 Defining a Controller and using it: singletons, i.e. only one instance of the service is created in the
lifetime of an AngularJS application.
i. With $scope:
angular.module(“myModule”). 07
Factory:
controller(“SampleController”,
angular.module(“myModule”).
function($scope,){
factory(“sampleFactory”, function(){
//Members to be used in view for binding
var cities = [“New Delhi”, “Mumbai”,
$scope.city=”Hyderabad”;
“Kolkata”, “Chennai”];
});
function addCity(city){cities.push(city);}
function getCities(){return cities;}
In the view: return{
getCities: getCities,
<div ng-controller=”SampleController”> addCity:addCity
<!-- Template of the view with binding };
expressions using members of $scope --> });
<div>{{city}}</div>
</div>
A factory is a function that returns an object. The members
that are not added to the returning object, remain private
ii. Controller as syntax:
to the factory. The factory function is executed once and the
result is stored. Whenever an application asks for a factory, the
angular.module(“myModule”).
application returns the same object. This behavior makes the
controller(“SampleController”, function(){
var controllerObj = this; factory a singleton.
//Members to be used on view for binding
controllerObj.city=”Hyderabad”;
}); 08
Value:
angular.module(“myModule”).value(“sampleValue”, {
In the view:
cities : [“New Delhi”, “Mumbai”, “Kolkata”,
“Chennai”],
<div ng-controller=”SampleController as ctrl”>
addCity: function(city){cities.push(city);},
<div>{{ctrl.city}}</div>
getCities: function(){return cities;}
</div>
});
02 www.dotnetcurry.com/magazine
09 Constant: application. Services, Factories and values are not available
for config block as they are not created by this time. Only
angular.module(“myModule”). providers and constants are accessible inside the config block.
constant(“sampleConstant”,{pi: Math.PI}); Config block is executed only once in the lifetime of an Angular
application.
A constant is also like a value. The difference is, a constant can
be injected into config blocks, but a value cannot be injected.
12 Run block:
10 Provider: angular.module(“myModule”).run(function(<any
services, factories>){
angular.module(“myModule”). console.log(“Application is configured. Now inside run
provider(“samplePrd”, function(){ block”);
this.initCities = function(){ });
console.log(“Initializing Cities…”);
}; Run block is used to initialize certain values for further
use, register global events and anything that needs to run at
this.$get = function(){
the beginning of the application. Run block is executed after
var cities = [“New Delhi”, “Mumbai”,
“Kolkata”, “Chennai”]; config block, and it gets access to services, values and factories.
function addCity(city){ Run block is executed only once in the lifetime of an Angular
cities.push(city); application.
}
function getCities(){return cities;}
return{ getCities: getCities,addCity:addCity 13 Filters:
};
} angular.module(“myModule”).
}); filter(“dollarToRupeee”, function(){
return function(val){
return “Rs. “ + val * 60;
A provider is a low level recipe. The $get() method of the };
provider is registered as a factory. Providers are available });
to config blocks and other providers. Once application
configuration phase is completed, access to providers is Usage:
prevented. <span>{{price | dollarToRupee}}</span>
After the configuration phase, the $get() method of the Filters are used to extend the behavior of binding expressions
providers are executed and they are available as factories. and directives. In general, they are used to format values or to
Services, Factories and values are wrapped inside provider with apply certain conditions. They are executed whenever the value
$get() method returning the actual logic implemented inside bound in the binding expression is updated.
the provider.
14 Directives:
11 Config block:
myModule.directive(“directiveName”, function
angular.module(“myModule”).config(function (injectables) {
(samplePrdProvider, sampleConstant){ return {
samplePrdProvider.init(); restrict: “A”,
console.log(sampleConstant.pi); template: “<div></div>”,
}); templateUrl: “directive.html”,
replace: false,
transclude: false,
Config block runs as soon as a module is loaded. As the name
scope: false,
itself suggests, the config block is used to configure the
www.dotnetcurry.com/magazine 03
require: [“someOtherDirective”], of the current directive.
controller: function($scope, $element,
$attrs, $transclude, otherInjectables) { ... },
• controller: Controller for the directive. Can be used to
link: function postLink(scope, iElement,
manipulate values on scope or as an API for the current
iAttrs) { ... },
priority: 0, directive or a directive requiring the current directive
terminal: false,
compile: function compile(tElement, tAttrs, • priority: Sets priority of a directive. Default value is 0.
transclude) { Directive with higher priority value is executed before a
return {
directive with lower priority
pre: function preLink(scope, iElement,
iAttrs, controller) { ... },
post: function postLink(scope, • terminal: Used with priority. If set to true, it stops execution
iElement, iAttrs, controller) { ... } of directives with lower priority. Default is false
}
} • link: A function that contains core logic of the directive.
};
It is executed after the directive is compiled. Gets access
});
to scope, element on which the directive is applied (jqLite
object), attributes of the element containing the directive and
Directives add the capability of extending HTML. They are the
controller object. Generally used to perform DOM manipulation
most complex and the most important part of AngularJS. A
and handling events
directive is a function that returns a special object, generally
termed as Directive Definition Object. The Directive Definition
• compile: A function that runs before the directive is compiled.
Object is composed of several options as shown in the above
Doesn’t have access to scope as the scope is not created yet.
snippet. Following is a brief note on them:
Gets an object of the element and attributes. Used to perform
DOM of the directive before the templates are compiled and
• restrict: Used to specify how a directive can be used. Possible
before the directive is transcluded. It returns an object with two
values are: E (element), A (Attribute), C (Class) and M (Comment).
link functions:
Default value is A
• transclude: Boolean value that says if the directive should • ng-app: To bootstrap the application
preserve the HTML specified inside directive element after
rendering. Default is false • ng-controller: To set a controller on a view
• scope: Scope of the directive. It may be same as the scope of • ng-view: Indicates the portion of the page to be
surrounding element (default or when set to false), inherited updated when route changes
from scope of the surrounding element (set to true) or an
isolated scope (set to {}) • ng-show / ng-hide: Shows/hides the content within
the directive based on boolean equivalent of value
• require: A list of directive that the current directive needs. assigned
Current directive gets access to controller of the required
directive. An object of the controller is passed into link function • ng-if: Places or removes the DOM elements under
04 www.dotnetcurry.com/magazine
this directive based on boolean equivalent of value 16 AngularJS Naming Conventions
assigned
• While naming a file say an authentication controller,
end it with the object suffix. For eg: an authentication
• ng-model: Enables two-way data binding on any
controller can be renamed as auth–controller.js.
input controls and sends validity of data in the input
Similar service can be called as auth-service.js,
control to the enclosing form
directive as auth-directive.js and a filter as auth-filter.js
• ng-class: Provides an option to assign value of • Create meaningful & short lower case file names that also
a model to CSS, conditionally apply styles and use reflect the folder structure. For eg: if we have a login controller
multiple models for CSS declaratively inside the login folder which is used for creating users, call it
login-create-controller.js
• ng-repeat: Loops through a list of items and copies
the HTML for every record in the collection • Similar a testing naming convention that you could follow
is if the filename is named as login-directive.js, call its test file
• ng-options: Used with HTML select element to counterpart as login-directive_test.js. Similarly a test file for
render options based on data in a collection login-service.js can be called as login-service_test.js
Use a workflow management tool like Yeoman plugin for
• ng-href: Assigns a model as hyperlink to an anchor Angular that automates a lot of these routines and much more
element for you. Also look at ng-boilerplate to get an idea of the project
and directory structure.
• ng-src: Assigns a model to source of an image
element 17 Dependency Injection:
• ng-click: To handle click event on any element AngularJS has a built-in dependency injector that keeps track
of all components (services, values, etc.) and returns instances
• ng-change: Requires ng-model to be present of needed components using dependency injection. Angular’s
along with it. Calls the event handler or evaluates the dependency injector works based on names of the components.
assigned expression when there is a change to value
of the model A simple case of dependency injection:
www.dotnetcurry.com/magazine 05
18 Routes 21 Some useful utility functions
Routes in AngularJS application are defined using • angular.copy - Creates a deep copy of source
$routeProvider. We can define a list of routes and set one of
the routes as default using otherwise() method; this route • angular.extend - Copy methods and properties from one
will respond when the URL pattern doesn’t match any of the object to another
configured patterns.
• angular.element - Wraps a raw DOM element or HTML string
as a jQuery element
The basic difference between a service and a factory is that • angular.isObject - Determines if a reference is an Object
service uses the constructor function instead of returning a
factory function. This is similar to using the new operator. So • angular.isString - Determines if a reference is a String
you add properties to ‘this’ and the service returns ‘this’.
06 www.dotnetcurry.com/magazine
22 $http:
$http.get(‘/api/data’).then(function(result){
return result.data;
}, function(error){
return error;
});
www.dotnetcurry.com/magazine 07
• $q.reject(reason) - Creates a promise that is resolved as
INTERMEDIATE - ADVANCED
rejected with the specified reason. The return value ensures
that the promise continues to the next error handler instead of
23 Manage Dependencies a success handler.
Use a package management tool like Bower (bower.io/) to • deferredObject.resolve - Resolves the derived promise with
manage and update third-party web dependencies in your the value
project. It is as simple as installing bower using npm install
bower; then listing all the dependent libraries and versions in a • deferredObject.reject - Rejects the derived promise with the
Bower package definition file called bowerconfig.json and lastly reason and triggers the failure handler in the promise.
run bower install or bower update in your project to get the
latest versions of any web dependencies in your project.
27 Manipulating $scope
25 Services <div>
<button ng-click=”getResponse()”>Close Dialog
</button>
If you need to share state across your application, or need a </div>
solution for data storage or cache, think of Services. Services
are singletons and can be used by other components such as In dialog-controller.js file, use the following code:
directives, controllers, filters and even other services. Services dialog.controller(“diagCtrl”, function ($scope) {
do not have a scope of their own, so it is permissible to add $scope.response = false;
eventlisteners in Services using $rootScope.
$scope.getResponse = function () {
});
The $q service provides deferred objects/promises.
This reduces the coupling between the view and controller
• $q.all([array of promises]) - creates a Deferred object that is
resolved when all of the input promises in the specified array
are resolved in future
28 Prototypal Inheritance
08 www.dotnetcurry.com/magazine
29 Event Aggregator: certain interval. If count is not passed, it defaults to 0, which
causes the call to happen indefinitely.
$scope includes support for event aggregation. It is possible to
publish and subscribe events inside an AngularJS application $interval(function () {
//Logic to execute
without need of a third party library. Following methods are
}, 1000, 10, true);
used for event aggregation:
www.dotnetcurry.com/magazine 09
injected in. This gives freedom to programmers to pass any 37 Testing controllers:
object of their choice instead of the actual component object
while writing tests. The only thing to be taken care is to create In an AngularJS application, we generally don’t need to create
an object with the same shim as the component. an object of a controller manually. It gets created whenever
a view loads or the template containing an ng-controller
AngularJS code can be unit tested using any JavaScript Unit directive loads. To create it manually, we need to use the
Testing framework like QUnit, Jasmine, Mocha or any other $controller service. To test the behavior of controller, we need to
framework. Jasmine is the most widely used testing framework manually create object of the controller.
with Angular. Tests can be run anywhere, in browser or even in
console using Karma test runner. inject(function($controller){
var controller = $controller(‘myController’,
The main difference between application code and unit tests { $scope: scope, service: serviceMock });
});
is, application code is backed by the framework and browser,
whereas unit tests are totally under our control. So, wherever
As we see, arguments to the controller are passed using a
we get objects automatically injected or created by AngularJS,
JavaScript object literal. They would be mapped to right objects
these objects are not available in unit tests. They have to be
according to names of the services. After this, the scope would
created manually.
have all properties and methods that are set in the controller.
We can invoke them to test their behavior.
35 Bootstrapping a unit test:
it(‘should return 10’, function(){
Just like the case of Angular application, we need to bootstrap var val = scope.getValue();
a module in unit tests to load the module. As the module expect(val).toEqual(10);
});
has to be loaded fresh before any test runs, we load module
while setting up the tests. In Jasmine tests, setup is doe using
beforeEach block. 38 Testing services:
beforeEach(function(){
Getting object of a service is easy as it is directly available to
module(‘myModule’);
the inject() method.
});
var serviceObj;
36 Creating $scope in unit tests: beforeEach(inject(function (myService) {
serviceObj = service;
}));
$scope is a special injectable in AngularJS. It is unlike other
objects as it is not already created to pass into a component
Now any public method exposed from the service can be called
when asked. A $scope can be injected only inside controllers
and the result can be tested using assertions.
and for every request of $scope, a new $scope object is created
that is inherited from $rootScope. Framework takes care of
it(‘should get some data’, function(){
creating the scope when the application is executed. We have
var data = serviceObj.getCustomers();
to do it manually to get a $scope object in tests. Following expect(data).not.toBe(null);
snippet demonstrates creation of $scope: expect(data).not.toBe(undefined);
});
var scope;
10 www.dotnetcurry.com/magazine
update user when a background task is completed or any such and ask Angular’s injector to return the object whenever the
thing that doesn’t depend on the view loaded inside ng-view. service is requested.
Mocking is one of the most crucial things in unit testing. It • We can mock the backend and test components depending
helps in keeping the system under test isolated from any on the $http service using the $httpBackend service in ngMocks
dependency that it has. It is very common to have a component
to depend on a service to get a piece of work done. This work • We can mock timeouts and intervals using $interval and
has to be suppressed in unit tests and replaced with a mock or $timeout in ngMocks
stub. Following snippet mocks a service:
• The $log service can be used for test logging
Say, we have following service:
• The $filter service allows us to test filters
app.service(‘customersSvc’, function(){
this.getCustomers = function(){ • Directives are complex to test. Use the $compile service and
//get customers and return
jqLite to test directives
};
this.getCustomer = function(id){
};
//get the customer and return 43 ng-class:
www.dotnetcurry.com/magazine 11
Assigns value of dynamicClass from scope to the CSS class. It is In the above snippet, the route won’t be resolved if the promise
two-way bound, i.e. if value of dynamicClass changes, the style is rejected. Resolve block can be injected into the controller and
applied on the div also changes. data resolved from the resolve block can be accessed using the
injected object.
ii. <div class=”[class1, class2, class3]”>some text</div>
12 www.dotnetcurry.com/magazine
• $routeChangeStart 50 HTTP Interceptors
• $routeChangeSuccess
• $routeChangeError Any HTTP request sent through $http service can be
• $routeUpdate intercepted to perform certain operation at a given state. The
state may be one of the following: before sending request, on
49 Exception handling
51 HTTP Transforms
All unhandled exceptions in an AngularJS application are
Transforms allow us to tweak the data before sending to
passed to a service $exceptionHandler, which logs the
an HTTP request or after receiving response at the end of a
error message in the browser’s console. In large business
request. It can be applied either globally using a config block or
applications, you may want to log the error details on the
on a specific request using the $http config object.
server by calling an API. This can be done by decorating the
$exceptionHandler service.
Setting transform in config block:
myApp.config(function ($provide) {
$provide.decorator(‘$exceptionHandler’, [‘$log’, myModule.config(function ($httpProvider) {
‘$http’, ‘$delegate’, $httpProvider.defaults.transformRequest.push(function
function ($log, $http, $delegate) { (data) { //Operate on data });
return function (exception, cause) { });
$log.debug(‘Modified exception handler’);
$http.post(‘/api/clientExceptionLogger’, In the individual request:
exception);
$delegate(exception, cause); $http({
}; url: ‘/api/values’,
} method: ‘GET’,
]); transformRequest: function (data) {//Operate on data}
}); });
www.dotnetcurry.com/magazine 13
Some useful AngularJS Tools & Libraries Ravi Kiran is a developer working on
Microsoft Technologies. These days,
• Visual Studio Express (free), Sublime (paid), NetBeans (free) or he spends his time on the front-end
WebStorm (paid) for AngularJS Development JavaScript framework Angular JS and
• Batarang Chrome Development Plugin (bit.ly/dncm15- server frameworks like ASP.NET Web
batarang) for debugging and profiling AngularJS applications API and SignalR. He actively writes
• AngularUI (angular-ui.github.io/ ) and ngModules what he learns on his blog at sravi-
(ngmodules.org ) are a good place to look out for commonly kiran.blogspot.com. He is a DZone
used modules MVB. You can follow him on twitter at @sravi_kiran
• Angular Seed (bit.ly/dncm15-angularseed ), ngBoilerplate
(github.com/ngbp/ngbp) and Yeoman (yeoman.io/) can be used
for workflow and project structure management Suprotim Agarwal, ASP.NET Architecture MVP
• The Iconic Framework (http://ionicframework.com) is an is an author and the founder of
Angular wrapper around PhoneGap; can be used to build hybrid popular .NET websites like dotnetcurry.com,
mobile apps with Angular devcurry.com and the DNC .NET Magazine.
You can follow him on twitter
@suprotimagarwal or check out his new
Some useful companion libraries in book www.jquerycookbook.com
AngularJS
• AngularUI-Bootstrap (github.com/angular-ui/bootstrap)
provides native AngularJS directives for Bootstrap (No need of
jQuery)
• AngularUI-Utils (github.com/angular-ui/ui-utils) contains a
bunch of essential utilities (included with ng-boilerplate)
• AngularUI (angular-ui.github.io/) ports off many jQueryUI
components to Angular
• Angular translate (angular-translate.github.io) makes it easier
to apply internationalization to Angular projects
• Restangular (github.com/mgonto/restangular) A clean,
promise-based, feature rich 3rd-party library that provides some
useful abstractions, especially for complex operations on the
client-side.
• AngularFire (firebase.com/docs/web/libraries/angular/): An
abstraction to interact with Firebase realtime database
• Breeze.js (breezejs.com): A library for rich data operations in
AngularJS apps. Also contains directives for data validations
Main.ts:
import { platformBrowserDynamic } from
'@angular/platform-browser-dynamic';
platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => console.error(err));
Index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Tour of Heroes</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<app-root></app-root>
</body>
</html>
Mock-heroes.ts:
import { Hero } from './hero';
Message.service.ts:
import { Injectable } from '@angular/core';
add(message: string) {
this.messages.push(message);
}
clear() {
this.messages = [];
}
}
In-memory-data.services.ts
import { Injectable } from '@angular/core';
import { InMemoryDbService } from 'angular-in-memory-web-api';
import { Hero } from './hero';
@Injectable({
providedIn: 'root',
})
export class InMemoryDataService implements InMemoryDbService {
createDb() {
const heroes = [
{ id: 12, name: 'Dr. Nice' },
{ id: 13, name: 'Bombasto' },
{ id: 14, name: 'Celeritas' },
{ id: 15, name: 'Magneta' },
{ id: 16, name: 'RubberMan' },
{ id: 17, name: 'Dynama' },
{ id: 18, name: 'Dr. IQ' },
{ id: 19, name: 'Magma' },
{ id: 20, name: 'Tornado' }
];
return {heroes};
}
// Overrides the genId method to ensure that a hero always has an id.
// If the heroes array is empty,
// the method below returns the initial number (11).
// if the heroes array is not empty, the method below returns the
highest
// hero id + 1.
genId(heroes: Hero[]): number {
return heroes.length > 0 ? Math.max(...heroes.map(hero => hero.id))
+ 1 : 11;
}
}
Hero.ts:
export interface Hero {
id: number;
name: string;
}
Hero.service.ts:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
constructor(
private http: HttpClient,
private messageService: MessageService) { }
/**
* Handle Http operation that failed.
* Let the app continue.
*
* @param operation - name of the operation that failed
* @param result - optional value to return as the observable result
*/
private handleError<T>(operation = 'operation', result?: T) {
return (error: any): Observable<T> => {
App.module.ts:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [
BrowserModule,
FormsModule,
AppRoutingModule,
HttpClientModule,
App.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Tour of Heroes';
}
App.component.html:
<h1>{{title}}</h1>
<nav>
<a routerLink="/dashboard">Dashboard</a>
<a routerLink="/heroes">Heroes</a>
</nav>
<router-outlet></router-outlet>
<app-messages></app-messages>
App.component.css:
Css here
App-routing.module.ts:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
@NgModule({
imports: [ RouterModule.forRoot(routes) ],
exports: [ RouterModule ]
})
export class AppRoutingModule {}
Heroes.component.ts:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-heroes',
templateUrl: './heroes.component.html',
styleUrls: ['./heroes.component.css']
})
export class HeroesComponent implements OnInit {
heroes: Hero[] = [];
ngOnInit(): void {
this.getHeroes();
}
getHeroes(): void {
this.heroService.getHeroes()
.subscribe(heroes => this.heroes = heroes);
}
Heroes.component.html:
<h2>My Heroes</h2>
<div>
<label for="new-hero">Hero name: </label>
<input id="new-hero" #heroName />
<!-- (click) passes input value to add() and then clears the input
-->
<button type="button" class="add-button"
(click)="add(heroName.value); heroName.value=''">
Add hero
</button>
</div>
<ul class="heroes">
<li *ngFor="let hero of heroes">
<a routerLink="/detail/{{hero.id}}">
<span class="badge">{{hero.id}}</span> {{hero.name}}
</a>
<button type="button" class="delete" title="delete hero"
(click)="delete(hero)">x</button>
</li>
</ul>
Heroes.component.css:
Css
Hero-search component:
Hero-search.component.ts:
import { Component, OnInit } from '@angular/core';
import {
debounceTime, distinctUntilChanged, switchMap
} from 'rxjs/operators';
@Component({
selector: 'app-hero-search',
templateUrl: './hero-search.component.html',
styleUrls: [ './hero-search.component.css' ]
})
export class HeroSearchComponent implements OnInit {
heroes$!: Observable<Hero[]>;
private searchTerms = new Subject<string>();
ngOnInit(): void {
this.heroes$ = this.searchTerms.pipe(
// wait 300ms after each keystroke before considering the term
debounceTime(300),
Hero-search.component.html:
<div id="search-component">
<label for="search-box">Hero Search</label>
<input #searchBox id="search-box" (input)="search(searchBox.value)"
/>
<ul class="search-result">
<li *ngFor="let hero of heroes$ | async" >
<a routerLink="/detail/{{hero.id}}">
{{hero.name}}
</a>
</li>
</ul>
</div>
Hero-search.component.css:
Css
Hero-detail component:
Hero-detail.component.ts:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Location } from '@angular/common';
@Component({
selector: 'app-hero-detail',
templateUrl: './hero-detail.component.html',
styleUrls: [ './hero-detail.component.css' ]
})
export class HeroDetailComponent implements OnInit {
hero: Hero | undefined;
constructor(
private route: ActivatedRoute,
private heroService: HeroService,
private location: Location
) {}
ngOnInit(): void {
this.getHero();
}
getHero(): void {
const id = parseInt(this.route.snapshot.paramMap.get('id')!, 10);
this.heroService.getHero(id)
.subscribe(hero => this.hero = hero);
}
goBack(): void {
this.location.back();
}
save(): void {
if (this.hero) {
this.heroService.updateHero(this.hero)
.subscribe(() => this.goBack());
}
}
}
Hero-detail.component.html:
<div *ngIf="hero">
<h2>{{hero.name | uppercase}} Details</h2>
<div><span>id: </span>{{hero.id}}</div>
<div>
<label for="hero-name">Hero name: </label>
<input id="hero-name" [(ngModel)]="hero.name" placeholder="Hero
name"/>
</div>
<button type="button" (click)="goBack()">go back</button>
<button type="button" (click)="save()">save</button>
</div>
Hero-detail.component.css:
Css
Dashboard component
Dashboard.component.ts:
import { Component, OnInit } from '@angular/core';
import { Hero } from '../hero';
import { HeroService } from '../hero.service';
@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: [ './dashboard.component.css' ]
})
export class DashboardComponent implements OnInit {
heroes: Hero[] = [];
ngOnInit(): void {
this.getHeroes();
}
getHeroes(): void {
this.heroService.getHeroes()
.subscribe(heroes => this.heroes = heroes.slice(1, 5));
}
}
Dashboard.component.html:
<h2>Top Heroes</h2>
<div class="heroes-menu">
<a *ngFor="let hero of heroes"
routerLink="/detail/{{hero.id}}">
{{hero.name}}
</a>
</div>
<app-hero-search></app-hero-search>
Dashboard.component.css:
Css
Message component:
Message.component.ts:
import { Component } from '@angular/core';
import { MessageService } from '../message.service';
@Component({
selector: 'app-messages',
templateUrl: './messages.component.html',
styleUrls: ['./messages.component.css']
})
export class MessagesComponent {
Message.component.html:
<div *ngIf="messageService.messages.length">
<h2>Messages</h2>
<button type="button"
class="clear"
(click)="messageService.clear()">Clear messages</button>
<div *ngFor='let message of messageService.messages'> {{message}}
</div>
</div>
AngularJS Cheat Sheet
by ProLoser via cheatography.com/1600/cs/513/
http://docs.angularjs.org/api/ng.directive:fo‐
rm.FormController
$q.all([array of promises])
Creates a Deferred object which represents a task which will finish
in the future.
$q. defer()
Creates a Deferred object which represents a task which will finish
in the future.
$q.reject(reason)
Creates a promise that is resolved as rejected with the specified
reason
$q.when( value)
Wraps an object that might be a value or a (3rd party) then-able
promise into a $q promise
Deferred.resolve( value)
Resolves the derived promise with the value
Deferred.reject(reason)
Rejects the derived promise with the reason
Deferred.promise
Promise object associated with this deferred
Promise.then(successCallback, errorCallback)
http://docs.angularjs.org/api/ng.$q
import {
Import platformBrowserDynamic
platformBrowserDynamic }
from
from
@angular/platform-browser-dyn
'@angular/platform-browser
amic.
-dynamic';
NGMODULES DETAILS
import {
NgModule } from Import NgModule from @angular/core.
'@angular/core';
@NgModule({
declarations: …,
imports: …,
exports: …,
providers: …,
bootstrap: …
}) Defines a module that contains components,
directives, pipes, and providers.
class MyModule
{}
declarations: [
MyRedComponent,
MyBlueComponent,
MyDatePipe
List of components, directives, and pipes that
belong to this module.
]
imports: [
BrowserModule,
SomeOtherModule
List of modules to import into this module.
Everything from the imported modules is
available to declarations of this module.
]
exports: [
MyRedComponent,
MyDatePipe
providers: [
MyService,
{ provide: … }
List of dependency injection providers visible
both to the contents of this module and to
importers of this module.
]
bootstrap: List of components to bootstrap when this
[MyAppComponent] module is bootstrapped.
<div title="Hello
{{ponyName}}">
<div [title]="'Hello ' +
ponyName">
<p>
Hello {{ponyName}}
<my-cmp [(title)]="name">
<my-cmp [title]="name"
(titleChange)="name=$eve
nt">
</ng-template>
<p>
Card No.: {{cardNumber |
myCardNumberFormatter}}
Transforms the current value of
expression cardNumber using the
pipe called
</p> myCardNumberFormatter.
<p>
Employer:
{{employer?.companyName}}
The safe navigation operator (?)
means that the employer field is
optional and if undefined, the rest
</p> of the expression should be ignored.
<svg:rect x="0"
y="0"
width="100"
An SVG snippet template needs an
svg: prefix on its root element to
disambiguate the SVG element from
height="100"/> an HTML component.
<svg>
<rect x="0"
y="0"
width="100"
height="100"/> An <svg> root element is detected
as an SVG element automatically,
without the prefix.
</svg>
BUILT-IN DIRECTIVES DETAILS
</div>
<div [ngClass]="{'active':
isActive,
FORMS DETAILS
import { FormsModule
Import FormsModule from
} from
@angular/forms.
'@angular/forms';
<input
Provides two-way data-binding, parsing,
[(ngModel)]="userNam
and validation for form controls.
e">
@Component({…})
@Directive({…})
@Pipe({…})
DIRECTIVE DETAILS
CONFIGURATION
@Directive({
property1: value1,
…
providers: [
MyService,
{ provide: … }
Inline template or
external template URL of
templateUrl: 'my-component.html'
the component's view.
{ provide: MyService,
Sets or overrides the provider for
useClass:
MyService to the MyMockService class.
MyMockService }
const routing =
RouterModule.forRoot(routes
);
<router-outlet></router-outlet>
function canDeactivateGuard:
CanDeactivateFn<T> =
(
component: T,
route: An interface for defining a
ActivatedRouteSnapshot, function that the router should
state: RouterStateSnapshot call first to determine if it should
) => { … } deactivate this component after
a navigation. Should return a
boolean|UrlTree or an
Observable/Promise that
resolves to a boolean|UrlTree.
{ path: …, canDeactivate:
[canDeactivateGuard] }
function canActivateChildGuard:
CanActivateChildFn =
(
route:
ActivatedRouteSnapshot,
state: RouterStateSnapshot An interface for defining a
) => { … } function that the router should
call first to determine if it should
activate the child route. Should
return a boolean|UrlTree or an
Observable/Promise that
{ path: …,
resolves to a boolean|UrlTree.
canActivateChild:
[canActivateGuard],
children: … }