Lecture 23 Angular - Directives - Templates

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 22

Angular

Lecture 23
Angular Concepts
Directives
 Custom attributes that enhance HTML syntax and are used
to attach behaviors to specific elements on the page.
 Angular lets you extend HTML with new attributes called
Directives.
◦ Angular has a set of built-in directives which offers functionality
to your applications.
◦ Angular also lets you define your own directives.
◦ Angular directives are extended HTML attributes with the prefix
ng.
◦ Directives are components without a view. They are components
without a template.
 Directives in Angular is a js class, which is declared as @directive.
We have 3 directives in Angular.
Directives
 We typically associate directives to existing
elements by use attribute selectors, like so:
<elemenent aDirective></element>
 Ng-template
 Built-in Directives
◦ Structural
◦ Attribute
 Custom Directives
Ng-Template
 This is a new tag in HTML which is specifically
designed to hold template code.
◦ It can sit under the body element but any content
inside it is not shown in the browser.
<ng-template [ngIf]='condition'>
<p>I am the content to show</p>
</ng-template>
• * is the Syntax sugar for ng-Template
• When we prepend a directive with * we are telling it
to use the element it’s attached to as the template.
Structural Directives
 The structural directives allow us to change the DOM structure
in a view by adding or removing elements.
 We will explore built-in structural directives, ngIf, ngFor, and
ngSwitch.
 Normally we have * with structural directives specially with
ngFor and ngIf
 ngNonBindable
◦ We use ngNonBindable when we want tell Angular not to compile, or bind, a
particular section of our page.
<div>To render the name variable we use this syntax <pre ngNonBindable>{{ name }}</pre>
</div
Built-in Structural Directives
 ngFor
◦ The ngFor is a repeater directive, it's used for displaying a list
of items.
◦ We use ngFor mostly with arrays in JavaScript, but it will work
with any iterable object in JavaScript.
◦ The ngFor directive is similar to the for...in statement in
JavaScript.Here is a quick example:
public frameworks: string[] = ['Angular', 'React', 'Ember'];
◦ The framework is an array of frontend framework names.
Here is how we can display all of them using ngFor:
<ul>
<li *ngFor="let framework of frameworks">
{{framework}}
</li>
</ul>
Built-in Structural Directives
 ngFor
◦ Index
 Sometimes we also want to get the index of the item in the
array we are iterating over.
<ul>
<li *ngFor="let person of people; let i = index">
{{ i + 1 }} - {{ person.name }}
</li>
</ul>
◦ Grouping
<ul *ngFor="let group of peopleByCountry">
<li>{{ group.country }}</li>
<ul>
<li *ngFor="let person of group.people">
{{ person.name }}
</li>
</ul>
Structural Directives
 ngIf
◦ The ngIf directive is used for adding or removing elements from
DOM dynamically:
◦ <element *ngIf="condition"> content </element>
◦ If the condition is true, Angular will add content to DOM, if the
condition is false it will physically remove that content from DOM:
<div *ngIf="isReady">
<h1>Structural Directives</h1>
<p>They lets us modify DOM structure</p>
</div>
The asterisk (*) symbol before ngIf is a must.
Built-in Structural Directives
 ngSwitch
◦ Conditionally instantiate one template from a set of choices,
depending on the value of a selection expression.
◦ ngSwitch will have multiple templates, depending on the
value passed, it will render one template. This directive is
similar to the switch() statement in JavaScript:
<div [ngSwitch]="selectedCar">
<template [ngSwitchCase]="'Bugatti'">I am Bugatti</template>
<template [ngSwitchCase]="'Mustang'">I am Mustang</template>
<template [ngSwitchCase]="'Ferrari'">I am Ferrari</template>
<template ngSwitchDefault>I am somebody else</template>
</div>
Attribute Directives
 ngStyle
◦ The ngStyle directive is used when we need to apply multiple
inline styles dynamically to an element.
◦ In the template:
<p [ngStyle]="getInlineStyles(framework)">{{framework}}</p>
◦ In the Component class:
getInlineStyles(framework) {
let styles = {
'color': framework.length > 3 ? 'red' : 'green',
'text-decoration': framework.length > 3 ? 'underline' : 'none'
};
return styles;
}
Attribute Directives
 ngClass
◦ The ngClass directive is used when we need to apply multiple classes
dynamically. The code for Styles is as follows:
.red {
color: red;
text-decoration: underline;
}
.bolder {
font-weight: bold;
}
In the Component class:
geClasses(framework) {
let classes = {
red: framework.length > 3,
bolder: framework.length > 4
};
return classes;
}
In the template:
<p [ngClass]="geClasses(framework)">{{framework}}</p>
Pipes
 Pipes are used to transform data, when we only need that
data transformed in a template.
 We use a pipe with the | syntax in the template {{ 1234.56 |
currency : 'USD’ }}. You can create chain.
 Pipes provided by Angular
◦ CurrencyPipe: Format input with defined currenct
◦ DatePipe: Format input to date pattern {{dateval|date:’shortTime’}}
◦ DecimalPipe: Transformation of decimals{{3.1234|number:’3.1-2’}}
◦ JsonPipe:javascript to json {{jsonval|json}}
◦ LowerCasePipe: String to lower {{ 'ASIM' | lowercase }}
◦ UpperCasePipe: String to Upper {{ 'ASIM’ | uppercase }}
◦ PercentPipe: number to percent {{ 0.123456 | percent: '2.1-2' }}
◦ SlicePipe: returns a slice of an array. {{ [1,2,3,4,5,6] | slice:1:3 }}
◦ AsyncPipe:This pipe accepts an observable or a promise and lets us render
the output of an observable or promise without having to call then or
subscribe.
Dependency injection:
 A way to supply dependencies (services most of the time) to
classes (other services or components).
 The DI framework in Angular consists of 4 concepts working
together:
 Token
◦ This uniquely identifies something that we want injected. A dependency of
our code.
 Dependency
◦ The actual code we want injected.
 Provider
◦ This is a map between a token and a list of dependencies.
 Injector
◦ This is a function which when passed a token returns a dependency (or a
list of dependencies) == Summary
Injector
 Injector
◦ Injector resolves a token into a dependency.
◦ It is normally handled by Angular.
 Provider
let injector = ReflectiveInjector.resolveAndCreate([
MandrillService,
SendGridService
]);
 Token
let emailService = injector.get("EmailService");
Here emailservice is a token
Code for src/book-store.service.ts
import { Injectable } from '@angular/core';
import { Book } from './book';
import { BOOKS } from './mock-books';
@Injectable()
export class BookStoreService {
booksList: Book[] = BOOKS;
getBooks () {
return this.booksList;
}
getBook (isbn: number) {
var selectedBook = this.booksList
.filter(book => book.isbn === isbn);
return selectedBook[0];
}
deleteBook (isbn: number) {
this.booksList = this.booksList
.filter(book => book.isbn !== isbn);
return this.booksList;
}
}
Builtin Service
 Angular has about 30 built-in services.
◦ The $location service has methods which return information
about the location of the current web page.Same as
window.location.
◦ The $http service is one of the most common used services in
Angular applications. The service makes a request to the server,
and lets your application handle the response.
◦ The $timeout service is Angular' version of the
window.setTimeout function.
HTTP
 The http client is a service that you can inject into your
classes in Angular.
import { HttpModule } from '@angular/http';
class MyClass {
constructor(private http: Http) {
}
}
 Adding to main @NgModule({imports: [HttpModule]})

 In Angular there are two ways of handling http asynchronous


operations.
◦ We can use Promises
◦ we can use Observables.
doGET() {
console.log("GET");
let url = `${this.apiRoot}/get`;
this.http.get(url).subscribe(res => console.log(res.text())); }
For json: this.http.get(url).subscribe(res => console.log(res.json()));
Query:
import {URLSearchParams} from '@angular/http’;
doGET() {
console.log("GET");
let url = `${this.apiRoot}/get`;
let search = new URLSearchParams();
search.set('foo', 'moo');
search.set('limit', 25);
this.http.get(url, {search}).subscribe(res => console.log(res.json()));
}
doPOST() {
console.log("POST");
let url = `${this.apiRoot}/post`;
this.http.post(url, {moo:"foo",goo:"loo"}).subscribe(res =>
console.log(res.json()));
}
Metadata
 Metadata: Instructs Angular on how to
process a class, whether it's a component, a
module, a directive, which services have to be
injected, and so on.
Routing
 Same as in Express
 Our goal with routing is to have the HomeComponent rendered

when the url is / and the SearchComponent shown when the url is
/search
 Import and define in routing file. Will display while coding

import {Routes, RouterModule} from "@angular/router";


const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'search', component: SearchComponent }
];
 Then add this to app.module.ts in @ngModule

RouterModule.forRoot(routes)
 This directive tells Angular where it should insert each of those

components in the route, we’ll add ours to the AppComponent


<router-outlet></router-outlet>
Routing
 We can control navigation by using the routerLink directive in the
template itself.
<nav class="navbar navbar-light bg-faded">
<a class="navbar-brand" [routerLink]="['home']">iTunes Search App</a>
<ul class="nav navbar-nav">
<li class="nav-item active">
<a class="nav-link" [routerLink]="['home']">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" [routerLink]="['search']">Search</a>
</li>
</ul>
</nav>
 Parameterized Routes
const routes: Routes = [
{ path: 'blog/:id', component: BlogComponent }
];
Observables
 Observables is a new primitive type which acts
as a blueprint for how we want to create streams, subscribe
to them, react to new values, and combine streams together
to build new ones.
 I want our observable to create a single stream and push onto

that stream a number every second, incremented by 1.


 let obs = Rx.Observable.interval(1000);

 This observable is cold, that means it’s not currently pushing

out numbers.
 The observable will become hot and start pushing numbers

onto it’s first stream, when it gets it’s first subscriber, like so:
let obs = Rx.Observable
.interval(1000) .take(3);
obs.subscribe(value => console.log("Subscriber: " + value));

You might also like