Angular 2 Advanced Components. Components...

21
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/ Angular 2 and TypeScript Web Application Development Slide 1 Copyright © 2003-2016 IPT – Intellectual Products & Technologies Ltd. All rights reserved. Angular 2 Advanced Components. Components Testing Trayan Iliev IPT – Intellectual Products & Technologies e-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.

Transcript of Angular 2 Advanced Components. Components...

Page 1: Angular 2 Advanced Components. Components Testingiproduct.org/wp-content/uploads/2016/11/Angular2_TypeScript_Iliev_2016_08.pdf · Testing Configuration with Webpack webpack.test.js

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.

Page 2: Angular 2 Advanced Components. Components Testingiproduct.org/wp-content/uploads/2016/11/Angular2_TypeScript_Iliev_2016_08.pdf · Testing Configuration with Webpack webpack.test.js

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

Page 3: Angular 2 Advanced Components. Components Testingiproduct.org/wp-content/uploads/2016/11/Angular2_TypeScript_Iliev_2016_08.pdf · Testing Configuration with Webpack webpack.test.js

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

Page 4: Angular 2 Advanced Components. Components Testingiproduct.org/wp-content/uploads/2016/11/Angular2_TypeScript_Iliev_2016_08.pdf · Testing Configuration with Webpack webpack.test.js

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

Page 5: Angular 2 Advanced Components. Components Testingiproduct.org/wp-content/uploads/2016/11/Angular2_TypeScript_Iliev_2016_08.pdf · Testing Configuration with Webpack webpack.test.js

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

Page 6: Angular 2 Advanced Components. Components Testingiproduct.org/wp-content/uploads/2016/11/Angular2_TypeScript_Iliev_2016_08.pdf · Testing Configuration with Webpack webpack.test.js

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.

Page 7: Angular 2 Advanced Components. Components Testingiproduct.org/wp-content/uploads/2016/11/Angular2_TypeScript_Iliev_2016_08.pdf · Testing Configuration with Webpack webpack.test.js

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

Page 8: Angular 2 Advanced Components. Components Testingiproduct.org/wp-content/uploads/2016/11/Angular2_TypeScript_Iliev_2016_08.pdf · Testing Configuration with Webpack webpack.test.js

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!'); }}

Page 9: Angular 2 Advanced Components. Components Testingiproduct.org/wp-content/uploads/2016/11/Angular2_TypeScript_Iliev_2016_08.pdf · Testing Configuration with Webpack webpack.test.js

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

Page 10: Angular 2 Advanced Components. Components Testingiproduct.org/wp-content/uploads/2016/11/Angular2_TypeScript_Iliev_2016_08.pdf · Testing Configuration with Webpack webpack.test.js

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>

Page 11: Angular 2 Advanced Components. Components Testingiproduct.org/wp-content/uploads/2016/11/Angular2_TypeScript_Iliev_2016_08.pdf · Testing Configuration with Webpack webpack.test.js

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.

Page 12: Angular 2 Advanced Components. Components Testingiproduct.org/wp-content/uploads/2016/11/Angular2_TypeScript_Iliev_2016_08.pdf · Testing Configuration with Webpack webpack.test.js

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">

Page 13: Angular 2 Advanced Components. Components Testingiproduct.org/wp-content/uploads/2016/11/Angular2_TypeScript_Iliev_2016_08.pdf · Testing Configuration with Webpack webpack.test.js

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());

Page 14: Angular 2 Advanced Components. Components Testingiproduct.org/wp-content/uploads/2016/11/Angular2_TypeScript_Iliev_2016_08.pdf · Testing Configuration with Webpack webpack.test.js

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,...})

Page 15: Angular 2 Advanced Components. Components Testingiproduct.org/wp-content/uploads/2016/11/Angular2_TypeScript_Iliev_2016_08.pdf · Testing Configuration with Webpack webpack.test.js

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

Page 16: Angular 2 Advanced Components. Components Testingiproduct.org/wp-content/uploads/2016/11/Angular2_TypeScript_Iliev_2016_08.pdf · Testing Configuration with Webpack webpack.test.js

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)

Page 17: Angular 2 Advanced Components. Components Testingiproduct.org/wp-content/uploads/2016/11/Angular2_TypeScript_Iliev_2016_08.pdf · Testing Configuration with Webpack webpack.test.js

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

Page 18: Angular 2 Advanced Components. Components Testingiproduct.org/wp-content/uploads/2016/11/Angular2_TypeScript_Iliev_2016_08.pdf · Testing Configuration with Webpack webpack.test.js

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);

});

});

Page 19: Angular 2 Advanced Components. Components Testingiproduct.org/wp-content/uploads/2016/11/Angular2_TypeScript_Iliev_2016_08.pdf · Testing Configuration with Webpack webpack.test.js

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'); });});

Page 20: Angular 2 Advanced Components. Components Testingiproduct.org/wp-content/uploads/2016/11/Angular2_TypeScript_Iliev_2016_08.pdf · Testing Configuration with Webpack webpack.test.js

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]}]

Page 21: Angular 2 Advanced Components. Components Testingiproduct.org/wp-content/uploads/2016/11/Angular2_TypeScript_Iliev_2016_08.pdf · Testing Configuration with Webpack webpack.test.js

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?