Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Introduction To Angular 8 - NDC Sydney

Download as pdf or txt
Download as pdf or txt
You are on page 1of 42

Introduction to Angular

NDC Sydney - http://bit.ly/ng8-ndc-sydney

www.angulartraining.com
About me - Alain Chautard (or just Al)

Google Developer Expert in Web technologies / Angular

/ Google Maps

Angular JS addict since 2011

Consultant / trainer @ angulartraining.com

Organizer of the Sacramento Angular Meetup group / GDG Sacramento


Quick poll

● How many of you are Java developers? C#, .Net?


● How many of you have any experience with Angular 1 ?
● With Javascript? TypeScript?
● Angular 2+?
How is Angular
different from PHP,
ASP, JSP?

In the past, all of the


front-end code (HTML, JS,
CSS) was generated from
the back-end.

User interactions with the


webpage often required a
full-page refresh.
How is Angular
different from PHP,
ASP, JSP?

With Angular, the front-end


code is now independent
from the back-end

The web server becomes a


web-service that outputs
JSON data, not dynamic
HTML or CSS
A bit of Angular history

Angular JS era (1.x) Angular era (2+)

2012 2013 2014 2015 2016 2017 2018 2019

1.0 1.2 1.3 1.4 1.5 2.0 4.0 5.0 6.0 7.0 8.0
1.1

Releases happen from time to time Clear, predictable schedule


Angular is widely used

1600+
That's how many apps are built with Angular at
Google alone (was 800 just 2 years ago)

Many more at: www.madewithangular.com


Angular is made
with Typescript
TypeScript is a strict
superset of ES6 (tomorrow’s
Javascript) which is the next
iteration of ES5 (today’s
Javascript)

More familiar to back-end


devs

Browser independent as it
transpiles down to ES5
anyway
Angular CLI - https://cli.angular.io/

● It’s a code generator


● It’s a set of tools for development (local server,
auto-refresh)
● It’s a set of build tools (compile, lint, minify...)
● Also very helpful for testing
Components

www.angulartraining.com
What are
components? <app-root>

<header title=”A title”></header>


A component is comparable
<left-menu [items]=”items”>
to an HTML element that
YOU create </left-menu>

It controls a small part of <data-view [hidden]=false>


the screen
</data-view>
An Angular app is a tree of
components </app-root>
Here's an Angular app - Let's build it from scratch!
Example of Angular
component

A component's application
logic is defined inside a
class.

The class interacts with the


view through an API of
properties and methods.
Angular
component: @Component({

HTML and CSS selector: 'app-hello',

templateUrl: './hello.component.html',
Both HTML and CSS for a styleUrls: ['./hello.component.css']
component can be stored in
their own files })

export class HelloComponent {


We get those files loaded
using the following syntax: // …
Angular Component

● 80%+ of the Angular code you’re going to write will be


components
● There are component libraries that provide their own collection
of components:
Data Bindings

www.angulartraining.com
Angular Data Bindings - [] and ()

Component class properties can be bound to HTML attributes:

● The above sets the value of the value HTML attribute of the
input element to this.name in our component class.
● It also binds the click event to the alertName() method.
Angular Models - [(ngModel)]

[(ngModel)] = 2-way data binding

Changes to the HTML update your TS scope and vice-versa:


Bindings + HTML = Super Powers

Since bindings work on any HTML attribute, you can use


then to apply styles conditionally:
<p [style.color]="hasError ? 'red' : 'blue'">

This also works to show/hide error messages:


<div [hidden]="noErrors">
The value you entered is not valid
</div>
Bindings -
Recap
Expressions {{}} and
property bindings with []
are one-way data bindings

Event bindings with () are


one-way data bindings

[(ngModel)] works both


ways
Directives

www.angulartraining.com
Angular Directives

● Directives allow DOM manipulation


● There are three kinds of Angular directives:

- Components = Directives with a HTML template


- Attribute directives = Change attribute values
- Structural directives = Change the HTML structure
Angular *ngFor

● *ngFor is a structural directive


● Equivalent of Angular JS’ ng-repeat
● A loop to iterate through data model items:
<li *ngFor="let person of persons">

{{ getDisplayName(person) }}

</li>
Angular *ngIf

● Directives like Angular JS ng-show, ng-hide are replaced by


HTML attribute bindings
● For instance, [hidden]=”myCondition”
● *ngIf is based on DOM rather than CSS:
Angular ngSwitch

● Switch-case implementation for Angular


● Allows to display content conditionally:
Pipes

www.angulartraining.com
Angular Pipes with |

● Equivalent of Angular JS filters


● Used to format data for display
● Pipes can be chained
● Examples include: uppercase, lowercase,
currency, date

We can write our own pipes!


Pipe Parameters

● Pipes can have parameters


● Parameters are optional and separated by :
● Example with the date pipe
{{someDate | date:’mediumDate’}}
● All of the pipes in the Angular framework can be
found here: https://angular.io/api?type=pipe
Services and
dependency injection

www.angulartraining.com
Angular Services

● Services are meant to handle application logic (fetch data,


update data, etc.)
● They are classes that can be injected in other objects
● Services are singletons: There is only one instance per
injector
● To turn a class into a service, we need the @Injectable()
decorator applied to that class
Dependency injection

● Angular relies on dependency injection to provide services to


other objects such as components, directives, etc.
● Dependency injection is a process where a class delegates
the responsibility of providing its dependencies to external
code (the injector)
● Classes are not allowed to call the injector code. It is the
injector that constructs the services and stores one instance
of each.
Dependency injection with Angular

● Angular relies on constructors to achieve dependency


injection
● Any class marked as @Injectable can be injected into an
Angular object as follows:

export class ListPostsComponent {


constructor(postService : PostsService) {
Dependency injection

The following syntax turns any class into an injectable service:

@Injectable({
providedIn: 'root'
})
export class TestService {

You can generate a service with:

ng generate service Test


ng g s Test
Typescript - Constructor syntax
In Typescript,constructor parameters marked as public, private or
protected are automatically turned into class properties:
export class ListPostsComponent {
constructor(public postService : PostsService) {
}

is equivalent to:
export class ListPostsComponent {
postService : PostsService;
constructor(postService : PostsService) {
this.postService = postService;
}
}
HTTP Client

www.angulartraining.com
Angular HttpClient

● Angular service for http requests (AJAX)


● Works seamlessly with JSON data and REST
● Returns an Observable object that we subscribe to in order
to receive the data from the HTTP response
Angular HttpClient

● HttpClient is a service that can be injected


● Note the use of generics to specify the type of the response:
import {HttpClient} from '@angular/common/http';

@Injectable()
export class CartService {

constructor(private http: HttpClient) { }

getCartContents(): Observable<LicensePlate[]> {

return this.http.get<LicensePlate[]>('http://localhost:8000/cart');

}
Component Router

www.angulartraining.com
Angular Component Router

Angular was designed for Single Page Applications

But very often we need more than one page!

The Component Router allows us to emulate this by loading


components based on URLs

For instance, /cart would load a Cart component, /login for


login, etc.
Example of
router Navigation

implementation
Dynamic content area where
Here the navigation components
component and the footer get loaded based on the URL

are always the same on all <router-outlet>


pages. </router-outlet>

The only dynamic part is the


blue section, determined by Footer
the <router-outlet>
directive
Angular Component Router

● Requires a routing table that maps URLs to


components (app.routing.ts):
const appRoutes: Routes = [
{
path: '', component: MenuComponent
}, {
path: 'observable-example', component: ObservableExampleComponent
}, {
path: 'subject-example', component: SubjectExampleComponent
}
];

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


Thank you
For follow-up questions: al@interstate21.com

Slides: http://bit.ly/ng8-ndc-sydney

www.angulartraining.com

You might also like