Angular Pro

Agenda

  • Advanced content generation
  • Angular Elements
  • Dependency Injection and Injectors
  • Router Extras
  • Angular Optimization
  • Service Workers & Web Workers
  • Angular 9, 10 and next
  • Security

Advanced content generation

View vs Content

ViewChild/ContentChild static

// query results available in ngOnInit
@ViewChild('foo', {static: true}) foo: ElementRef; 

// query results available in ngAfterViewInit
@ViewChild('foo', {static: false}) foo: ElementRef;

ContentChild/ViewChild

@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

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 { Injector} from '@angular/core';
import { MyService } from './my.service';


const injector = Injector.create([MyService]);
  
  
myService = injector.get(MyService);

Component Injector

componentInstance.injector

Node Injector (Element Injector) Tree

Child Injector

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

const childInjector = Injector.create([MyService], injector);

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

What about Providers?

Token

Recipe

{

}

  • String
  • Class
  • InjectionToken
  • useClass
  • useExisting
  • useFactory
  • useValue
InjectionToken<UserService>(‘UserService_TOKEN’, {
    providedIn: ‘root’
    factory: () => new UserService()
});

, multi

How injection happens?

  • constructor
  • decorator
  • parameters
    • @Self / @SkipSelf
    • @Host()
    • @Optional()

 providedIn?

  • tree-shaking
  • prevents duplication
  • "root"
  • "platform"
  • "any"

viewProviders

Router Extras

Router Animations

Lazy Loading and Preloading Strategies

Angular Optimizations

What could be faster

  • Loading/First screen
    • Bundle Size Optimization
    • AOT compilation
    • SSR
    • Lazy loading (+preloading)
    • Service Workers
    • Static Page Generation
  • Runtime
    • Change Detection
      • onPush Strategy
      • detach CD
    • Web Workers

Bundle Size Optimization

ExpressionChangedAfterItHasBeenCheckedError

  • Shared Service
  • Event Emitter
  • Dynamic Component 

Cases:

Solution:

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

Web Workers

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

  • index.html
  • sw bundle to dist
  • ngsw-manifest.json

Updates

Push Notifications

Angular Next

Angular 9

IVY

  • Smaller bundle sized
  • Better debugging
    • ng object (properties, method, apply)
    • better error stack trace
  • Improved type checking
    • fullTemplateTypeCheck (strictTemplates)
  • Improved build errors
  • AOT by default
    • no entryComponents
  • New components
  • TypeScript 3.7 (optional chaining )
  • TypeScript 3.8 (type-only imports, private fields, top-level await)

Angular 10

  • TypeScript 3.9
    • TypeScript 4
  • ng new --strict
  • bye-bye Closure Compiler
  • generic mandatory for ModuleWithProviders
  • dropping esm5 and fesm5 (spec)
  • unknown elements are now logged as console.error
  • WrappedValue removed from AsyncPipe (issue)

Bugfix

Angular 11 (11.0.0-rc.0)

  • TypeScript 3.9 not supported
  • removes IE 9, 10, and IE mobile support completely
  • router improvements
  • pipes improvements
  • forms improvements
  • Trusted Types
  • ViewEncapsulation.Native has been removed. Use ShadowDom
  • ? Webpack 5 (Module Federation)

Bugfix

How to inject Scully?

  • ng add @scullyio/init
  • ng generate @scullyio/init:blog
  • ng generate @scullyio/init:post --name="This is my post1"
  • ng build
  • npm run scully
  • npm run scully:serve

published: true

Security

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

Post Data with malicious code
Store
Fetch
Open App
Get malicious code
Check

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

login
action
bad action
done
done!

CSRF Tokens

login
action
bad action
done
Token:  
 ==
Token: ... 
NO ACCESS!
 != ...

Do you know all your project dependencies?

True story

event-stream v3.3.6

right9ctrl

event-stream v4.0.0

flatmap-stream v0.1.1

flatmap-stream v0.1.0

event-stream v3.3.5

flatmap-stream v0.1.1

require("crypto").decrypt("aes256", data, npm_package_description);

copay-dash

if(!/build\:.*\-release/.test(process.arg[2])) return;

npm       run-script      command

"build:ios-release": "run-s env:prod && ionic cordova build ios --release"

inject malicious payload to steal private keys from wallet

npm audit

npm install angularcli

HTTPS

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

Redirect

request HTTP page
redirect to HTTPS
request HTTPS page
HTTPS response

But

95% of HTTPS servers vulnerable to trivial MITM attack

request HTTP page
redirect to HTTPS
request HTTPS page
HTTPS response
request HTTP page
HTTP response
HTTPS  HTTP
login
steal
credentials
login HTTPS
HTTPS response
HTTP response

HSTS

request HTTP page
redirect to HTTPS
request HTTPS page
HTTPS response
with Strict-transport-security header
another day
user requests HTTP page

Bonus

Angular Pro

By Stepan Suvorov