Kendo UI for Angular

denis@newventuresoftware.com
github.com/deniskyashif
@deniskyashif

Agenda

  • TypeScript
  • Angular
  • Kendo UI for Angular
  • Q&A

Say NO to the slow and painful

We'll make it interactive

Tools that we need

NodeJS:
https://nodejs.org/en/download/current/
IDE/Text Editor
Visual Studio Code, WebStorm, Sublime Text etc.
Git
https://git-scm.com/downloads
Boilerplate Code
git clone https://github.com/newventuresoftware/angular-demos.git

What is TypeScript?

  • Language created by Microsoft.
  • Has optional static typing.
  • Inherits concepts from C#.
  • Can use type definitions for intellisense.
  • Can use JavaScript libraries.
  • Compiles to JavaScript.

It's always better to catch errors at compile time rather that at runtime.

Benefits of TypeScript

  • Due to static typing, it's more predictable.
  • Due to modules, namespaces and stronger OOP, it scales better for larger apps.
  • Due to compilation step, some errors are caught compile-time, not run-time.

Installing TypeScript

Using the Node Package Manager.

npm install --global typescript

Compiling TypeScript

TypeScript is written in .ts files, which can't be used directly in the browser.
It need to be translated to vanilla .js first.

tsc main.ts

tsconfig.json

Specifies the way TS is compiled.
(autogeneratable with tsc --init)

{
  "compilerOptions": {
    "target": "es5", // Sets the output JS's version
    "module": "commonjs", // Sets the module loader
    "outDir": "dist", // Sets output JS files' location
    "sourceMap": true, // Allows debugging
    "noEmitOnError": true // Do not compile if errors
  }
}

Language Features

Static Type System

“Strongly typed languages reduce bugs by 15%.”

Classes

Interfaces

Generics

Class<T>

Modules

import / export

EcmaScript 6

EcmaScript 7

EcmaScript Next

Every time a new JS Framework comes up...

...but not this time.

A developer platform for building mobile and desktop web apps using TypeScript/JavaScript and other languages.

Consists of several libraries, some of them core and some optional.

Framework

Architecture

With all the front-end build tools, setting up a project can be tedious.

Angular CLI solves this problem!

angular-cli

  • Project initializer
  • Generating:
    • Components
    • Services
    • Directives
    • Pipes
  • Linting
  • Building
  • And many more...

Live Demo

Setting up a project with the Angular CLI

Angular CLI

Install NodeJS
https://nodejs.org/en/download/
Install Angular CLI
npm install -g @angular/cli
Initialize a project
ng new movies
Navigate to the project root.
cd movies
Run the project
ng serve

Modules

@NgModule({
  imports:      [ BrowserModule ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

What is @NgModule?

  • A decorator function that takes a single metadata object whose properties describe the module.
  • Tells Angular how to compile and run the module code.
  • Consolidates components, directives and services into cohesive blocks of functionality.
  • It can import other modules for reusing their Components, Directives etc.

Components

@Component()

Components in Angular

  • The basic UI building block in Angular.
  • Control the view.
  • Represent anything visible to the end user.
  • Angular creates, updates and destroys components as the user moves through the app.
  • Angular provides view encapsulation by default which enables the Shadow DOM

Shadow DOM

  • Shadow DOM is just normal DOM with two differences:
    1. how it's created/used and
    2. how it behaves in relation to the rest of the page
  • Shadow DOM is designed as a tool for building component-based apps

    • Angular uses components
      • It addresses the DOM tree encapsulation problem
      • Allows us to hide DOM logic behind other elements

Shadow DOM

  • Isolated DOM - A component's DOM is self-contained
    • document.querySelector() won't return nodes in the component's shadow DOM
  • Scoped CSS - CSS defined inside shadow DOM is scoped to it

View Encapsulation

  • Angular comes with view encapsulation by default which enables Shadow DOM
  • There are three view encapsulation types available
    • None - no Shadow DOM and no encapsulation
    • Emulated (default) - no Shadow DOM but there is encapsulation of the views
    • Native - native Shadow DOM

Component Tree

Data Binding

{{}} () [] [()]

A mechanism for coordinating the view with the application data.

Data Binding Types

Live Demo

Creating Angular Components

Pipes & Directives

@Pipe()
@Directive()

What are Pipes?

  • A way to write display-value transformations that can be declared in the HTML.
  • A pipe takes in data as input and transforms it to a desired output.
  • Angular comes with a stock of pipes such as DatePipe, UpperCasePipe, CurrencyPipe...
  • Pipes can be chained together in potentially useful combinations.

Name: {{ name | uppercase }}

What are Directives?

Directives aim to extends the static nature of HTML. They allow creating custom elements, attributes and even control flow inside the HTML.

Directives Types

  • Components - directives with a template.
  • Structural - change the DOM layout by adding and removing DOM elements(*ngIf, *ngFor).
  • Attribute - change the appearance or behavior of an element, component, or another directive(NgStyle, NgClass).

Live Demo

Working with Directives and Pipes

Dependency Injection and Services

@Injectable()

What is Dependency Injection(DI)?

A design principle in which a class should receive its dependencies from external sources rather than creating them itself.

DI Example

class Car {
    public engine: Engine;

    constructor() {
        this.engine = new Engine();
    }
}

What is the problem here?

  • Tight coupling between Car and Engine
  • If the definition of Engine changes, Car must also change.
  • Engine cannot be shared among Car instances.
  • Is it possible to create an Engine in a test environment?

DI Example

class Car {
    public engine: Engine;

    constructor(engine: Engine) {
        this.engine = engine;
    }
}

The class now receives its dependencies in the constructor.

const engine: Engine = new HybridEngine();
const car = new Car(engine);

Angular ships with its own dependency injection framework. This framework can also be used as a standalone module by other applications and frameworks.

Services

  • A service is nothing more than a class in Angular. It remains nothing more than a class until registered with an Angular injector.
  • You don't have to create an Angular injector. Angular creates an application-wide injector for you during the bootstrap process.

DI & Services

Providers

  • A provider is something that can create or deliver a service.
  • The providers are registered in the app module.
@NgModule({
  imports: [BrowserModule],
  providers: [UserService],
  declarations: [App],
  bootstrap: [App]
})
export class AppModule { }
platformBrowserDynamic().bootstrapModule(AppModule);

Live Demo

Services and DI

Routing in Angular

What is Routing?

  • Routing the standard way to navigate in a web applications.
  • Each unique route must always return the same page.

Live Demo

Angular Routing.

Reactive Programming

  • Programming with asynchronous data streams.
  • You are able to create data streams of anything.
  • A stream is a sequence of ongoing events ordered in time.
  • A stream can be used as an input to another one.
  • It emits three different things
    • a value (of some type)
    • an error
    • a complete method

RxJS and Observables

Set of libraries for composing asynchronous and event-based programs using observable sequences

const subscription = source
    .filter(quote => quote.price > 30)
    .map(quote => quote.price)
    .forEach(price => console.log(price));

Cold vs Hot

  • Cold observables start running upon subscription

    • The observable sequence only starts pushing values to the observers when Subscribe is called
  • Hot observables are ones that are pushing even when you are not subscribed to the observable

    • Like mouse moves, or Timer ticks, etc.
  • It’s not always possible from the subscriber side to know whether you are dealing with a cold or hot Observable

Observables Promise
Observables handle multiple values over time Promises are only called once and will return a single value
Observables are cancellable Promises are not cancellable
Observables are lazy Promises NOT

Angular HTTP

  • Angular's http service delegates the client/server communication tasks to a helper service called the XHRBackend
  • Register for HTTP services
    • Import the HttpModule
  • Can work with both Observables and Promises.

Angular HTTP Example

// Fetch all existing comments
getComments() : Observable<Comment[]> {
    // ...using get request
    return this.http.get('/api/comments')
        // ...and calling .json() on the response to return data
        .map((res:Response) => res.json())
        //...errors if any
        .catch((error:any) => Observable.throw(error.json().error));
}
service.getComments()
    .subscribe(comments => this.comments = comments);

Live Demo

Observables and HTTP.

Angular Lifecycle

ngOnInit()

Angular calls lifecycle hook methods on directives and components as it creates, changes, and destroys them.

Lifecycle Sequence

Constructor The constructor has been invoked.
OnChanges The data-bound input properties have been (re)set.
OnInit The component/directive has been initialized.
DoCheck Detect and act upon changes that Angular can't or won't detect on its own.
AfterContentInit After Angular projects external content into the component's view.
AfterContentChecked After Angular checks the content projected into the component.
AfterViewInit After Angular initializes the component's views and child views.
AfterViewChecked Called just before Angular destroys the directive/component.
OnDestroy After Angular checks the component's views and child views.

* TypeScript, Components & Directives, Component Only

Kendo UI for Angular

What is Kendo UI for Angular?

  • Native Angular Component Suite.
  • Each component group represents a separate Angular module.
  • Distributed via NPM (nodejs package manager).
  • Offers Unlimited Support.

Installation

Kendo UI for Angular components are distributed via npm.

npm install --save [kendo-component]

Every component represents a separate Angular module.

Live Demo

Components in Action

Kendo UI is much more that a component suite.

Data Query

The Data Query provides functions that help you handle the following bulk data operations:
sorting, filtering, grouping, aggragates

telerik.com/kendo-angular-ui/components/dataquery/api/

Kendo UI for Angular

Deployment

building for development and production

ng build [--prod]

Publish the contents of the generated dist/ folder to a web server.

Tooling

  • Ahead-Of-Time Compiler
  • Module Loader
  • Testing
    • Unit testing
    • e2e testing
    • Code Coverage
  • Bundler (Tree Shaking)
  • Linter (TypeScript and CSS)
  • Minifier

ng build --prod

AOT Compilation Pre-compiles Angular component templates.
Bundling Concatenates modules into a single file.
Inlining Pulls template html and css into the components.
Minification Removes excess whitespace, comments, and optional tokens.
Uglification Rewrites code to use short, cryptic variable and function names.
Dead Code Elimination Removes unreferenced modules and unused code.
Prune Libraries Drop unused libraries and pare others down to the features you need.

Debugging

The TypeScript compiler generates source map files, which allow browsers to recover the original source code from the compiled javascript.

Ensuring Code Quality

>_ ng lint

Angular + NativeScript

Learning Resources

Questions?

Thank You!

denis@newventuresoftware.com
github.com/deniskyashif
@deniskyashif
www.newventuresoftware.com