Angular Master Class  @Tinkoff 

Stepan Suvorov

CTO @ Studytube

`${new Date().getFullYear() - 2012} years with Angular`

Agenda

  • Advanced content generation
  • Dependency Injection and Injectors
  • Reactive approach
  • Router Extras
  • Change Detection
  • Angular Performance
  • Rendering (Ivy and SSR)
  • Service Workers
  • Security

Advanced content generation

View vs Content

ng-content

ContentChild/ViewChild

@ContentChild(selector, {read})

@ContentChild(selector)

  • any class with the @Component or @Directive decorator
  • a template reference variable as a string
  • any provider defined in the current/child component

ngTemplateOutlet

exportAs

@Attribute()

Component Inheritance

Structural Directive

Dynamic Components

ngComponentOutlet

Real Dynamic Components

Impure pipe

Angular Elements

Dependency Injection and Injectors

Main parts

  • Provider
  • Injector
  • Dependancy

Going deep with Injector

import { ReflectiveInjector} from '@angular/core';
import { MyService } from './my.service';
const injector = 
  ReflectiveInjector.resolveAndCreate([MyService]);
myService = injector.get(MyService);

Component Injector

componentInstance.injector

Child Injector

const injector = 
  Injector.resolveAndCreate([MyService]);

const childInjector = 
  injector.resolveAndCreateChild([MyService]);

childInjector.get(MyService) !== injector.get(MyService)

Injector Tree

ReflectiveInjector

vs

StaticInjector

What about Providers?

Token

Recipe

{

}

Provider Token

  • String
  • Class
  • OpaqueToken InjectionToken

Provider Recipe

  • useClass
  • useExisting
  • useFactory
  • useValue

Injection Token

InjectionToken<UserService>(‘UserService_TOKEN’, {
    providedIn: ‘root’
    factory: () => new UserService()
});

How injection happens?

  • constructor
  • decorator
  • parameter

Extra Decorators

  • @Self, @SkipSelf
  • @Host
  • @Optional

viewProviders

Reactive approach

Introducing RxJS6

  • Use pipeable operators
  • Async error throwing
  • New way of importing

new in 6:

  • Cleanup - big list of deprecated methods
  • throwIfEmpty
  • ng update rxjs
  • yarn add rxjs-tslint

migration:

Operator Groups

  • filter (debounceTime, filter, single, throttle, audit )
  • combine (combineLatest, zip, forkJoin )
  • combine ( concat, merge, startWith, … )
  • transform ( pluck,  reduce, scan )
  • transform ( map, flatMap, switchMap, exhaustMap )
  • error handling ( catchError, retry, retryWhen)
  • utility ( tap, delay, finalize )

Subject

  • BehaviourSubject
  • ReplySubject
  • AsyncSubject

Schedulers

Reactive Tests

Router Extras

Router Animations

Lazy Loading and Preloading Strategies

Dynamic Router States

Change Detection

ExpressionChangedAfterItHasBeenCheckedError

  • Shared Service
  • Event Emitter
  • Dynamic Component 

Cases:

Solution:

  • enableProdMode()
  • setTimeout
  • EventEmitter(true)
  • detectChanges 
  • enableProdMode()

Angular Performance

What could be optimized?

User side

Dev side

First screen

App ready

Runtime

Network performance

  • Bundling
  • Minification and Dead code elimination
  • Remove template whitespace
  • Tree-shaking
  • Ahead-of-Time (AoT) Compilation
  • Compression
  • Lazy-Loading of Resources
  • Caching
  • Use Application Shell (or correct loading indication)
  • Use Service Workers

Runtime Optimizations

  • Use enableProdMode
  • Ahead-of-Time Compilation
  • Web Workers
  • Server-Side Rendering
  • Change Detection
    • ChangeDetectionStrategy.OnPush
    • Detaching the Change Detector
    • Run outside Angular
  • Use trackBy option for *ngFor directive
    Optimize template expressions
  • Use pure pipes
  • Optimize template expressions

Angular Rendering

Ivy

What's so great about Ivy?

  • Simple
  • Smaller builds
  • Faster rebuild
  • Human readable
  • No more modules:
    • renderComponent(AppComponent);

How is it possible?

​Template syntax, Dependency injection, Content projection, Structural directives, Lifecycle hooks, Pipes..

--experimentalIvy

No more meta

  • @Component -> ngComponentDef
  • @Directive -> ngDirectiveDef
  • @Injectable -> ngInjectableDef

What's coming

  • Lazy loading without router
    • Dynamic import
  • Hand written templates
  • Higher order components

SSR

Why to use SSR?

  • SEO

  • First screen

  • Social friendly preview

 

How to SSR

  • npm packages
  • prepare client part

  • prepare server part

  • create server

 

Service Workers

What are Service Workers?

  • can't access the DOM directly
  • control how network requests from your page
  • It's terminated when not in use (no own state)
  • extensive use of promises
  • HTTPS required
  • Reliability
  • Performance
  • Push Notifications

SW Life Cycle

Install with AngularCli

$ ng add @angular/pwa

  • Add service worker registration code to the root module
  • Generate default service worker configuration file
  • Generate and link default Web App Manifest
  • Generate default icons set
  • Enable build support in Angular CLI config

Updates

Push Notifications

Security

What is Security?

  • Prevent vulnerabilities
    • XSS
    • XSRF
    • ...
  • Access Management
    • authentication/authorisation
    • ACL

Authorization based on JWT

JSON Web Token

Can you spot security issue here?

export class TokenInterceptor implements HttpInterceptor {
    constructor(public auth: AuthService) { }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
      
        request = request.clone({
          setHeaders: {
            Authorization: `Bearer ${this.auth.getToken()}`
          }
        });
     
        return next.handle(request);
    }
}

it's real life example and more

XSS

  • reflected
  • stored
  • DOM-based

Angular against XSS

Sanitization out of box:

  • HTML
  • Styles
  • Url
  • Resource Url

bypassSecurityTrust*

  • Angular controls the data in the template
  • Data is always escaped for the right context
  • HTML-bound data is sanitized by Angular

How can you bypass XSS filters?

$save_text = str_replace('script', 'span', $text);
<ScRiPt>/* bad things happen here */</ScRiPt>

<INPUT TYPE="IMAGE" src="javascript:/* ... */;">

<imgsrc="xss.png" onerror="/* bad things happen here */">

Are we safe now?

and what about

Template Injection?!

  • never mix Angular with other dynamic page generation techniques
  • use AoT

CSRF

What to do against CSRF

Do you know all your project dependencies?

True story

npm audit

npm install angularcli

HTTPS

How can we get people to use the HTTPS version of the site?

Redirect

But

95% of HTTPS servers vulnerable to trivial MITM attack

HSTS

good news for browser support

Bonus

Angular Master Class @ Tinkoff

By Stepan Suvorov

Angular Master Class @ Tinkoff

  • 1,681