Angular 2 Advanced Components. Components...
Transcript of Angular 2 Advanced Components. Components...
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
Angular 2 and TypeScript Web Application Development
Slide 1Copyright © 2003-2016 IPT – Intellectual Products & Technologies Ltd. All rights reserved.
Angular 2 Advanced Components. Components Testing
Trayan Iliev
IPT – Intellectual Products & Technologiese-mail: [email protected]
web: http://www.iproduct.org
Oracle®, Java™ and JavaScript™ are trademarks or registered trademarks of Oracle and/or its affiliates.Microsoft .NET, Visual Studio and Visual Studio Code are trademarks of Microsoft Corporation.
Other names may be trademarks of their respective owners.
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
Angular 2 and TypeScript Web Application Development
Slide 2Copyright © 2003-2016 IPT – Intellectual Products & Technologies Ltd. All rights reserved.
Agenda I
1. Angular CLI
2. Component interaction alternatives
3. Accessing component’s ViewChildren and ContentChildren using <ng-content>, @ViewChild, @ViewChilderen, @ContentChild, @ContentChildren decorators.
4. Building custom attribute and structural directives using @HostListener, @HostBinding / @Input
5. Component lifecycle and use of custom lifecycle hooks: ngOnInit, ngOnChanges, ngDoCheck, ngOnDestroy, ngAfterContentInit, ngAfterContentChecked, ngAfterViewInit, ngAfterViewChecked
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
Angular 2 and TypeScript Web Application Development
Slide 3Copyright © 2003-2016 IPT – Intellectual Products & Technologies Ltd. All rights reserved.
Agenda II
6. Shadow DOM and Angular 2 view encapsulation modes – ViewEncapsulation.None, ViewEncapsulation.Emulated and ViewEncapsulation.Native
7. Test Driven Development (TDD) - unit testing Angular 2 classes and components using Jasmine and Karma
Slide 4
Angular 2 and TypeScript Web Application Development
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
Copyright © 2003-2016 IPT – Intellectual Products & Technologies Ltd. All rights reserved.
Angular 2 Command Line Interface (CLI) [https://github.com/angular/angular-cli]
npm install -g angular-cli
ng new PROJECT_NAMEcd PROJECT_NAMEng serve
ng serve --port 4201 --live-reload-port 49153
Create Angular 2 compponents using CLI:Component ng g component my-new-componentDirective ng g directive my-new-directivePipe ng g pipe my-new-pipeService ng g service my-new-service
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
Angular 2 and TypeScript Web Application Development
Slide 5Copyright © 2003-2016 IPT – Intellectual Products & Technologies Ltd. All rights reserved.
Component Interaction Alternatives
Source: Angular 2 Cookbook: Component Interactionhttps://angular.io/docs/ts/latest/cookbook/component-communication.htmlLicense: CC BY 4.0.
Pass data from parent to child with input binding
Intercept input property changes with a setter
Intercept input property changes with ngOnChanges
Parent listens for child event
Parent interacts with child via a local variable
Parent calls a @ViewChild
Parent and children communicate via a service
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
Angular 2 and TypeScript Web Application Development
Slide 6Copyright © 2003-2016 IPT – Intellectual Products & Technologies Ltd. All rights reserved.
Angular 2 Services
Source: Angular 2 Developer Guide: Architecture overviewhttps://angular.io/docs/ts/latest/guide/architecture.htmlLicense: CC BY 4.0.
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
Angular 2 and TypeScript Web Application Development
Slide 7Copyright © 2003-2016 IPT – Intellectual Products & Technologies Ltd. All rights reserved.
Body content and template – two sources of markup / components / directives
Content projection using:<ng-content></ng-content><ng-content select=”header”></ng-content><ng-content select=”.css-class-select”></ng-content>
Accessing component’s ViewChildren and ContentChildren: @ViewChild(ComponentClass), @ViewChild('templVar')@ViewChildren(Item) items: QueryList<Item>;@ContentChild(Item) item: Item @ContentChildren(Item)items: QueryList<Item>;
Source: Rangle's Angular 2 Training Bookhttps://angular-2-training-book.rangle.io/handout/components/projection.htmlhttps://angular-2-training-book.rangle.io/handout/advanced-components/access_child_components.htmlLicense: Creative Commons Attribution-ShareAlike 4.0 International (CC BY-SA 4.0)
Component’s ViewChildren & ContentChildren
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
Angular 2 and TypeScript Web Application Development
Slide 8Copyright © 2003-2016 IPT – Intellectual Products & Technologies Ltd. All rights reserved.
@Directive
Directives add behaviour to an existing DOM element. One example use case for @Directive would be to add a highlight on mouse hover. Example – log-on-click.directive.ts :
import {Directive} from 'angular2/core';
@Directive({ selector: "[myLogOnClick]", host: { '(click)': 'onClick()' }})export class LogOnClickDirective { onClick() { console.log('Element clicked!'); }}
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
Angular 2 and TypeScript Web Application Development
Slide 9Copyright © 2003-2016 IPT – Intellectual Products & Technologies Ltd. All rights reserved.
Even Better @Directive
import {Directive, HostListener} from 'angular2/core';
@Directive({ selector: "[myLogOnClick]",})export class LogOnClickDirective { @HostListener('click') onClick() { console.log('Element clicked!'); }}
Prefer @HostListener and @HostBinding instead of the host property of the @Directive and @Component decorators
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
Angular 2 and TypeScript Web Application Development
Slide 10Copyright © 2003-2016 IPT – Intellectual Products & Technologies Ltd. All rights reserved.
Tooltip @Directive
import {Directive, HostListener, Input} from 'angular2/core';@Directive({ selector: '[myTooltip]', host: { '(mouseover)': 'show()' }})export class TooltipDirective { @Input('myTooltip') text: string; show() { alert(this.text); }}
<h1 myLogOnClick myTooltip="Enter new hero.">Hero Form</h1>
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
Angular 2 and TypeScript Web Application Development
Slide 11Copyright © 2003-2016 IPT – Intellectual Products & Technologies Ltd. All rights reserved.
Component Lifecycle and Lifecycle Hooks
1. ngOnChanges – on input props change2. ngOnInit - after the first ngOnChanges3. ngDoCheck -every change detection run4. ngAfterContentInit - after first content proj.5. ngAfterContentChecked - each projection6. ngAfterViewInit - after first component's
views and child views initialization/check7. ngAfterViewChecked - each views check8. ngOnDestroy - before destroing
directive/component – should unsubscribe observables and detach event handlers
Source: Angular 2 Advanced Guide: Lifecycle Hookshttps://angular.io/docs/ts/latest/guide/lifecycle-hooks.htmlLicense: CC BY 4.0.
Slide 12
Angular 2 and TypeScript Web Application Development
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
Copyright © 2003-2016 IPT – Intellectual Products & Technologies Ltd. All rights reserved.
Web Components and Shadow DOM
4 emerging W3C specifications:Custom elements – provide a way for authors to build their own fully-featured DOM elements.
Shadow DOM – combining multiple DOM trees in one hierarchy[http://www.html5rocks.com/en/tutorials/webcomponents/shadowdom/]
Template – declare fragments of HTML that can be cloned and inserted in the document by script
HTML imports – <link rel="import" href="my-custom-cmp.html">
Slide 13
Angular 2 and TypeScript Web Application Development
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
Copyright © 2003-2016 IPT – Intellectual Products & Technologies Ltd. All rights reserved.
Using Shadow DOM – Example
<template id="custom-tag-tpl"> <style> h1 { color: blue; } </style> <h1>My Custom Component</h1></template>
var CustomCmpProto = Object.create(HTMLElement.prototype);CustomCmpProto.createdCallback = function() { var template = document.querySelector('#custom-tag-tpl'); var clone = document.importNode(template.content, true); this.createShadowRoot().appendChild(clone);};var MyCmp = document.registerElement('custom-cmp', {prototype: CustomCmpProto});document.body.appendChild(new MyCmp());
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
Angular 2 and TypeScript Web Application Development
Slide 14Copyright © 2003-2016 IPT – Intellectual Products & Technologies Ltd. All rights reserved.
Angular 2 View Encapsulation Modes
ViewEncapsulation.None – no specific measures are taken to isolate the component instances and avoid css style conflicts between components, component styles propagate to all other components ViewEncapsulation.Emulated (Default) – simulates Shadow DOM using custom attributes and component instance specific CSS attribute selectors to allow view encapsulationViewEncapsulation.Native – employ Shadow DOM if supported by browser – styles from Light HTML do not propagate to the component – Example:
@Component({…, encapsulation: ViewEncapsulation.Native,...})
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
Angular 2 and TypeScript Web Application Development
Slide 15Copyright © 2003-2016 IPT – Intellectual Products & Technologies Ltd. All rights reserved.
Test Driven Development (TDD) with Angular 2
Testing Angular 2 specific artefacts:
Classes,
Pipes,
Components / Directives
Services
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
Angular 2 and TypeScript Web Application Development
Slide 16Copyright © 2003-2016 IPT – Intellectual Products & Technologies Ltd. All rights reserved.
Example Testing Toolchain
Jasmine – the most popular core framework for writing Angular 2 unit tests Karma – test automation tool to control the tests execution:
In which browsers / DOM implementations to perform tests Allows to generate different type of reports about results
Phantom-js – headless DOM implementation JavaScript API allowing to bootstrap our Angular 2 application and run DOM specific tests.Istanbul – Karma uses it to generate test coverage reportsSinon – additional (optional) test spys, test subs, and mock XHR requests (Jasmine provides spyOn function)Chai - assertion library pairing with other testing frameworks
Source: Rangle's Angular 2 Training Bookhttps://angular-2-training-book.rangle.io/handout/testing/intro-to-tdd/toolchain.htmlLicense: Creative Commons Attribution-ShareAlike 4.0 International (CC BY-SA 4.0)
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
Angular 2 and TypeScript Web Application Development
Slide 17Copyright © 2003-2016 IPT – Intellectual Products & Technologies Ltd. All rights reserved.
Testing Configuration with Webpack
webpack.test.js – theWebpack testing configuration
karma-conf.js – the main config file for Karma test runner
karma-test-shim.js – initializes the TestBed (testing environment), requires all individual tests (based on provided pattern), and all necessary modules for testing, including @angular/core/testing, and @angular/platform-browser-dynamic/testing
For each componets e.g. /app/feature/my.component.ts there should be a corresppnding unit tests file named /app/feature/my.component.spec.ts
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
Angular 2 and TypeScript Web Application Development
Slide 18Copyright © 2003-2016 IPT – Intellectual Products & Technologies Ltd. All rights reserved.
Simplest Test
describe('Testing math', () => {
it('addition should work', () => {
expect(5 + 5).toEqual(10);
});
});
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
Angular 2 and TypeScript Web Application Development
Slide 19Copyright © 2003-2016 IPT – Intellectual Products & Technologies Ltd. All rights reserved.
Simple Angular 2 Application Testdescribe('App', () => { beforeEach(() => { TestBed.configureTestingModule({ imports: [FormsModule, AppRoutingModule, CommonModule, HomeModule, ProductModule, UserModule], providers: [ BackendService, {provide: APP_BASE_HREF, useValue: '/' } ], declarations: [AppComponent, AppNavComponent, RouterLinkStubDirective, RouterOutletStubComponent]}); }); it ('should work', () => { let fixture = TestBed.createComponent(AppComponent); expect(fixture.componentInstance instanceof AppComponent) .toBe(true, 'should create AppComponent'); });});
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
Angular 2 and TypeScript Web Application Development
Slide 20Copyright © 2003-2016 IPT – Intellectual Products & Technologies Ltd. All rights reserved.
DI Providers (Recap)
Source: Angular 2 Developer Guide: Architecture overviewhttps://angular.io/docs/ts/latest/guide/architecture.htmlLicense: CC BY 4.0.
Provider class and provide object literal:
providers: [Logger]
[{ provide: Logger, useClass: Logger }]
[{ provide: Logger, useClass: SuperiorLogger }]
[ SuperiorLogger, { provide: Logger, useExisting: SuperiorLogger}]
[{ provide: Logger, useValue: { log: (message) => { console.log(`Custom: ${message}`); } }]
[{ provide: HeroService, useFactory: productServiceFactory, deps: [Logger, UserService]}]
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
Angular 2 and TypeScript Web Application Development
Slide 21Copyright © 2003-2016 IPT – Intellectual Products & Technologies Ltd. All rights reserved.
Thanks for Your Attention!
Questions?