Angular Pro
Agenda
- Advanced content generation
- Dependency Injection and Injectors
- Reactive approach
- Router Extras
- Angular Optimization
- SSR
- Angular Tools
- Service Workers
- Angular 8 and next
- Security
Advanced content generation
View vs Content
ng-content
ContentChild/ViewChild
@ContentChild(selector, {read})
@ContentChild(selector)
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
live conding
ReflectiveInjector
vs
StaticInjector
What about Providers?
Token
Recipe |
{
}
Provider Token
- String
- Class
-
OpaqueTokenInjectionToken
Provider Recipe
- useClass
- useExisting
- useFactory
- useValue
Injection Token
InjectionToken<UserService>(‘UserService_TOKEN’, {
providedIn: ‘root’
factory: () => new UserService()
});
How injection happens?
- constructor
- decorator
- parameter
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 States
New way of Lazy Loading
Angular Optimizations
What could be faster
- CD
- onPush Strategy
- detach CD
- AOT compilation
- Lazy loding (+preloading)
- SSR
- ServiceWorkers
- WebWorkers
CD Explained
ExpressionChangedAfterItHasBeenCheckedError
- Shared Service
- Event Emitter
- Dynamic Component
Cases:
Solution:
- enableProdMode()
- setTimeout
- EventEmitter(true)
- detectChanges
enableProdMode()
SSR
Why to use SSR?
-
SEO
-
First screen
-
Social friendly preview
How to SSR
-
npm packages
-
prepare client part
-
prepare server part
-
create server
ng add @nguniversal/express-engine --clientProject ssr
npm run build:ssr && npm run serve:ssr
How to deal with Lazy Loading
How cache the state?
Angular Tools
Angular Tools
- Angular CLI
- Schematics
- Angular Language Service
- VSCode: Snippets for Angular
- Augury
- Compodoc
- ngrev
- Chrome
- perfume.js
- ngx-build-plus
- ng add ngx-gh
- Angular Tracer
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 --project *project-name*
- index.html
- sw bundle to dist
- ngsw-manifest.json
Updates
Push Notifications
Angular 8
What's new
- Differential builds (es5 and es2015)
- Builder APIs in the Cli
- Cli for WebWorkers
- LazyLoading import()
- bazel*
- ivy renderer*
- ViewChild/ContentChild static
- TypeScript 3.4
* experimental
Differential builds
WebWorkers
Ivy
What's so great about Ivy?
- Smaller builds
- Faster rebuild
- Human readable
-
No more modules:
- renderComponent(AppComponent);
- Better errors
How is it possible?
- Locality
- Incremental DOM
- Tree-Shaking:
Template syntax, Dependency injection, Content projection, Structural directives, Lifecycle hooks, Pipes..
Is it ready?
$ ng new my-app --enable-ivy
{
"compilerOptions": { ... },
"angularCompilerOptions": {
"enableIvy": true
}
}
No more meta
- @Component -> ngComponentDef
- @Directive -> ngDirectiveDef
- @Injectable -> ngInjectableDef
What's coming
- Lazy loading without router
- Dynamic import
- Hand written templates
- Higher order components
Bazel
- incremental builds
- full-stack support
- scale on the cloud
$ npm i -g @angular/bazel
$ ng new my-app --collection=@angular/bazel
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;
How to update
Angular Cli 8.1
- ng generate component --skip-selector
- ng generate module admin --module users --route admin
- ng test –include
Angular 9
What's new
IVY
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);
}
}
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
Angular Pro
- 1,310