Download presentation
Presentation is loading. Please wait.
1
WWU Hackathon May 6 & 7
2
Understanding TypeScript
3
TypeScript What is it? Why Use it?
A typed superset of JavaScript compiled to JavaScript Designed by Anders Hejlsberg Microsoft Technical Fello (designer of C# and Delphy) TypeScript code is converted into its JavaScript before it is executed A JavaScript superset. In its most basic form, all JavaScript can be thought of as TypeScript Extends from JavaScript The transpiler converst all TypeScript code to JavaScript (ECMAScript 5 and above) which allows it to run in all browsers Provides a set of optional static types and interfaces through the TypeScript Language Service Supports Object Oriented Programming concepts like classes, interfaces, and inheritance When using types, it enables static analysis of your code via compilation step
4
Overview Installing and compiling Concetps
Use npm to install typescript npm install –g typescript OR Install Visual Studio plugin File extension .ts sample.ts Compilor tsc tsc sample.ts Variable definition Use let instead of var let age: number = 30; Basic Types boolean number string Arrays let list: number[] = [1,2,3]; Generics let Array<number> = [1,2,3]; Enum enum Color {Red, Green, Blue}; let c:Color = Color.Green; Any dynamic content resolved at runtime let notSure: any = 4; Interfaces Classes
5
Details Interface definitions Class defintions Modules
interface FullNameFunc{ fullName: string; getFullName(fName: string, lName: string): string; } Class defintions Class Student implements FullNameFunc { year: string; getFullName(fName:string, lName: string) { this.fullName = “FN: “ + fName + “-” + lName; return this.fullName; constructor(year: string) { this.year = year; } Modules Execute within their own scope Files containing top level imports and exports are considered modules Exports functionality as a module export interface FullnameFunc { getFullName(fName: string, lName: string): string; } Imports exported functionality from modules import {FullNameFunc} from “./FullNameFunc”; export class Student implements FullNameFunc { … } OR import * as names from “./FullNameFunc”; export class Student implements names.FullNameFunc { … }
6
Angular
7
Angular Concepts Typescript MVP framework
Like all MVP models, it goal is to separate business logic, from views, and models Extends HTML by providing new HTML elements that make more intuitive the intent of the markup Components are defined using Typescript objects Provides a direct link between HTML elements and the Typescript objects Data binding to the view is abstracted through HTML elements and minimal amount of DOM manipulations Provides mechanisms to built your own reusable services using built-in components The clean separation of responsibilities makes it easier to test your application using a test- driven approach
8
Angular Building Blocks
Modules Components Metadata Templates Data binding Directives Services Dependency injection
9
Modules Purpose is to consolidate functionality that belongs together
Provide a container for defining different parts of your app: services, components, root component, directives, pipes, etc. Angular Apps have at least one module, the root module Uses the NgModule decatorator to describe the properties of the module Propetries declarations: defines the view classes implemented as components, directives, and pipes exports: declarations used by component templates in other modules imports: other modules used by component templates in this module providers: defines the services that are part of the app bootstrap: main application view
10
Module details The JavaScript/Typescript import statement outside of decorator allows the application to reference the files being exported by other files The import statement inside defines the other Angular Modules used by this angular module/application These classes are themselves decorated with NgModule Holds all of the components, pipes, and directives defined inside your application This shouldn’t contain NgModules, Services, or other Classes The root component defines the entry point into the angular application Inserts these components into the DOM While you can have many components, you normally only have one The convention is to call this component AppComponent SAMPLE – app.module.ts import { NgModule } from import { BrowserModule } from @NgModule({ imports: [ BrowserModule ], providers: [ Logger ], declarations: [ AppComponent ], exports: [ AppComponent ], bootstrap: [ AppComponent ] }) export class AppModule { }
11
Modules Composition FILE: app.module.ts import { NgModule } from import { BrowserModule } from /* App Root */ import { AppComponent } from './app.component'; import { HighlightDirective } from './highlight.directive'; import { TitleComponent } from './title.component'; import { UserService } from './user.service'; /* Contact Imports */ import { ContactModule } from './contact/contact.module'; @NgModule({ imports: [ BrowserModule, ContactModule ], declarations: [ AppComponent, HighlightDirective, TitleComponent ], providers: [ UserService ], bootstrap: [ AppComponent ], }) export class AppModule { } FILE: contact.module.ts import { NgModule } from import { CommonModule } from import { FormsModule } from import { AwesomePipe } from './awesome.pipe'; import { ContactComponent } from './contact.component'; import { ContactService } from './contact.service'; import { HighlightDirective } from './highlight.directive'; @NgModule({ imports: [ CommonModule, FormsModule ], declarations: [ ContactComponent, HighlightDirective, AwesomePipe ], exports: [ ContactComponent ], providers: [ ContactService ] }) export class ContactModule { }
12
FILE: app.module.ts import { NgModule } from import { BrowserModule } from /* App Root */ import { AppComponent } from './app.component'; import { HighlightDirective } from './highlight.directive'; import { TitleComponent } from './title.component'; import { UserService } from './user.service'; import { CommonModule } from import { FormsModule } from import { AwesomePipe } from './awesome.pipe'; import { ContactComponent } from './contact.component'; import { ContactService } from './contact.service'; @NgModule({ imports: [ BrowserModule, CommonModule, FormsModule ], declarations: [ AppComponent, HighlightDirective, TitleComponent, ContactComponent, HighlightDirective, AwesomePipe ], providers: [ UserService, ContactService ], bootstrap: [ AppComponent ], }) export class AppModule { } Modules Composition
13
Bootstrapping Process
To load the main application module use the bootstrapModule method inside the platformBrowserDynamic module and pass it the module class: import { platformBrowserDynamic } from import { AppModule } from './app/app.module'; //bootstraps and launches the root module platformBrowserDynamic().bootstrapModule(AppModule); The bootstrap process sets the execution environment, creates an instance of the bootstrap component and inserts it within the element tags identified by the component’s selector
14
Components https://angular.io/docs/ts/latest/guide/architecture.html
A type of directive with template oriented features Provides Separation of Responsibilities Enables a clean separation between view, model, controller, and services Metadata Identifies the elements of the component Template Content or Template URL Selector HTML Element Name CSS Styles or CSS Style URL Providers Services Template Defines the view for a component Services Used to access information that is manipulated by the component’s view
15
Component’s Sample FILE: list-table.component.ts import {Input, Component, OnInit } from import IListModelAngular from '../../share/IListModelAngular'; @Component({ selector: 'list-table', templateUrl: './lists-table.component.html', styleUrls: ['./lists-table.component.css'] }) export class ListsTableComponent implements OnInit { @Input() list: IListModelAngular; constructor() { } ngOnInit() { } FILE: lists.component.ts import { Component, OnInit, Input } from import { ListService } from '../list.service'; import IListModelAngular from '../share/IListModelAngular'; @Component({ selector: 'app-list', template: './lists.component.html', styleUrls: ['./lists.component.css'] }) export class ListsComponent implements OnInit { @Input() listNumber: number[] = [1,2,3,4]; lists: IListModelAngular[]; constructor(list$: ListService) { list$.getListsIndex() .subscribe( result => this.lists = result, () => {}, () => console.log('REST call:' + this.lists) ); } ngOnInit() { console.log(“Component Initialized”); FILE: lists.component.html <div class="container" > <div class="panel panel-default"> <div class="panel-heading"> <h3>Active Lists</h3> </div> <div> <div class="panel panel-default" *ngFor="let result of lists"> <!-- Default panel contents --> <list-table [list]="result"></list-table> <!-- Table --> </div> <div ng-click="saveItems();">new list</div> <div>File Save Result: {{fileSaveResult}}</div> </div> </div> Sample:
16
Templates Provides a view for the component’s properties
Are associated with the component via the templateUrl or template content Contains HTML elements with data binding from Angular components and Directives
17
Data Binding 1 2 Provides a mechanism to synchronize data between component’s data and tmplates One way data binding Interpolation – displays the component properties in the template Property binding – set a property of a view element or passes properties from the parent component to the child component Event binding – invokes the component’s method when a template element triggers an event Two way data binding Data flows from the component properties to the template element and vice versa 3 3 1 2
18
Data Binding’s Sample EVENT BINDING (event) = “handler” import { Component } from @Component({ selector: 'my-app', template: ` <div>{{message}}</div> <button (click)="onClickMe()">Spanish</button> ` }) export class AppComponent { message = 'Hello World'; onClickMe() { this.message = 'Hola Mundo'; } INTERPOLATION {{value}} import { Component } from @Component({ selector: 'my-app', template: ` <h1>{{title}}</h1> <h2>My favorite hero is: {{myHero}}</h2>` }) export class AppComponent { title = 'Tour of Heroes'; myHero = 'Windstorm'; } PROPERTY BINDING [property] = “value” import { Component } from @Component({ selector: 'my-app', template: ` <img [src]=“imageUrl"> <button [disabled]="isUnchanged">Disabled Button</button>` }) export class AppComponent { imageUrl = '/img/image.png'; isUnchanged = 'false'; } TWO WAY BINDING [(ngModel)]=“property" import { Component } from @Component({ selector: 'my-app', template: ` <div>{{message}}</div> <input type="text" [(ngModel)]=“message"> <button (click)="onClickMe()">Print</button> ` }) export class AppComponent { message = 'Hello World'; onClickMe() { console.log(this.message); } Sample:
19
Services/Providers A Service is an instance of a Provider Providers are registered via modules or components Services are classes that are normally used to share data or logic across components Fetch data from server Validate User input Log data Angular doesn’t have a direct definition of a service No base class No Service decorator No Service Registry Services are made available to applications via Dependency Injection They are decorated with decorator Services are singletons. Components which depend on services will get a pointer to the same instance generated by the Injector Services are created when the component that needs them is instantiated. This assumes, there are not previously created and contained by the Injector container Services are defined in the constructor of a component This allows Angular to ask the Injector for these services at creation time Sample Service import { Injectable } from @Injectable() export class Logger { logs: string[] = []; log(message: string) { this.logs.push(message); console.log(message); } Sample Module Definitions providers: [Logger] providers: [{ provide: Logger, useClass: Logger }] providers: [{ provide: Logger, useClass: BetterLogger }] //Why do this?
20
Dependency Injection Provides a mechanism to deliver objects (services) needed by another object In this model dependencies are provided externally to the client code by the Injector Classes receive their dependencies from an external source instead of creating them internally Injector is responsible for maintaining a container of services that have been previously created It is created during the bootstrap process decorator is used to define the Providers that will be used to create services
21
Built-in HTTP Service Provides interaction with http services from the Angular application To use this service import HttpModule import { HttpModule } from The HTTP service is normally used inside custom services The Http Service needs to be added to the constructor in order to be used constructor (private http: Http) {} The Http method uses the RxJS library to return Observables to manage the asynchronous execution of request import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/catch'; import 'rxjs/add/operator/map'; Calling the http.get function getHeroes(): Observable<Hero[]> { return this.http.get(this.heroesUrl) .map(this.extractData) .catch(this.handleError); }
22
Reactive-Programming (RxJS)
RxJS supports the observer observable pattern Observables are asynchronous data streams Observers are subscriptions to the data stream which receive data when it is available Observables Properties Are Lazy initialized, meaning that they are only enabled when an observer is subscribed Can execute multiple times Can be cancelled FILE: lists.components.ts constructor(list$: FeedbackService) { list$.getListsIndex() .subscribe( result => this.lists = result, () => console.log('REST call failed'), () => console.log('REST call:' + this.lists) ); } FILE: list-service.service.ts getListsIndex() { return this.http.get("/app/list/") .map(response => response.json()); var observable = this.http.get(' var subscription = observable.subscribe(res => { console.log('The response is received.'); }); setTimeout(() => { subscription.unsubscribe(); }, 500);
23
RxJS Common Operators map flatMap flagMapLatest filter
Takes all of the elements on the stream and converts them into another element form while keeping their index order flatMap Takes all of the elements on the stream and puts them into another observable sequence flagMapLatest Same as flatMap but canceling any previous streams that are created filter Reduces the elements on the stream based on some predicate
24
Break
25
Lifecycle Hooks Lifecycle hooks provide visibility into directive creation, component rendering, creates and rendering of its children, changes on data bound properties, directive destruction They are implemented as interfaces The interface name is the name of the method minus the “ng” portion ngOnInit() method OnInit interface However, they are optional. The benefit is strong typing and editor support. The events are dispatched on the ordered outlined in the diagram These events are shared between components and directives with the exception of Content and View events
26
Pipes Responsible for modifying display data inside a template
Consumes data and produces new output data //converts the birthday property to a friendly formatted date string <p>Your birthday is {{ birthday | date:"MM/dd/yy" }} </p> Some Built-in pipes DatePipe, UpperCasePipe, LowerCasePipe, CurrencyPipe, and PercentPipe Pipes can be chained The chained hero's birthday is {{ birthday | date:'fullDate' | uppercase}} Sample:
27
Directives Attribute Directives Structural Directives
Alter the behavior and look of existing elements in the DOM Built-in directives NgClass - add and remove a set of CSS classes NgStyle - add and remove a set of HTML styles NgModel - two-way data binding to an HTML form element Sample Syntax <input [(ngModel)]="hero.name"> <div [ngClass]="currentClasses">This div is initially saveable, unchanged, and special</div> Alter layout by manipulating elements in the DOM (CRUD) Built-in directives NgIf - conditionally add or remove an element from the DOM NgFor - repeat a template for each item in a list NgSwitch - a set of directives that switch among alternative views Sample Syntax <li *ngFor="let hero of heroes"></li> <hero-detail *ngIf="selectedHero"></hero-detail> Live Sample :
28
Routing Interprets a client URL as local navigation to a client-generated view Can pass optional parameters to the component to help it decide what to present Can associated link URLs to client-generated views Enables programmatic navigation to client-generated views when events are generated (e.g. button click) Registers navigation events with the browser history to support back and forward browser buttons The base tag defines the initial directory path from which to resolve relative URLs: <base href=“/”> assumes the “app” folder is on the application root The RouterOutlet directive or the <router-outlet> element defines the location in the DOM where the view associated with the routed component will be displayed
29
Routing Syntax FILE: app.module.ts
import { RouterModule, Routes } from const appRoutes: Routes = [ { path: 'hero/:id', component: HeroDetailComponent }, { path: 'heroes', component: HeroListComponent, data: { title: 'Heroes List' } }, { path: '', redirectTo: '/heroes', pathMatch: 'full‘ }, { path: '**', component: PageNotFoundComponent } ]; @NgModule({ imports: [ RouterModule.forRoot(appRoutes) // other imports here ], bootstrap: [ AppComponent ], ... }) export class AppModule { } FILE: app.component.ts import { Component } from @Component({ selector: 'app-root', template: ` <h1>Angular Router</h1> <nav> <a routerLink="/" routerLinkActive="active">Home</a> <a routerLink="/heroes" routerLinkActive="active">Heroes</a> </nav> <router-outlet></router-outlet>`, styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'app works!'; } 3 2 1
30
Navigating to Routes Programmatically
Ensure the component that is implementing the navigation includes the Router service in its constructor so it can be added via dependency injection constructor( private router: Router, private service: HeroService ) {} Inside the event handler that will trigger the navigation, invoke the navigate method on the Router service onSelect(hero: Hero) { this.router.navigate(['/hero', hero.id]); } The first argument is the routing path and the second one is the parameter for the URL On the snipped above the route will navigate the user to /hero/:id To retrieve route path and parameter information use the ActivatedRoute service To retrieve the initial value of the route use the snapshot method let id = this.route.snapshot.params['id'];
31
Angular CLI The CLI is a tool used to initialize, develop, scaffold, and maintain Angular applications The scaffolding provides easy to use commands to easily create and build applications ng new Creates an application that runs out-of-the box ng generate or ng g Enables the creation of components, services, classes, and pipes with their respective test modules ng serve Provides a simple web server used to test your app during the development phase Other commands Provides mechanisms to enable testing, deployment, etc.
32
Using Angular CLI Create a new application Run the new application
ng new <app name> Run the new application ng serve Add components to the application ng g component <component name> Add services to the application ng g service <service name> Add classes to the application ng g class <class name>
33
Example Sample commands ng new social-app ng g component welcome
social-app (Module and Bootstrap) Example 1 AppComponent (Component) Sample commands ng new social-app ng g component welcome ng g component topics cd topics ng g component topic-entry cd .. ng g service social-api ng g class app-route 4 welcome (Component) topics (Component) topic-entry (Component) social-api (service) 3 2 app-route (router) Execution flow and component relationships
34
Hackathon Problem
35
Social Media Build a social media web app that allows users to post topics and other users can comment on the posts. Facebook is as an example Priorities Scenario Points 1 Write/Post a topic 30 Write a comment for a post 2 Reply to comment by writing a new comment 20 Like a comment or a post Associate URLs to posts at creation time Change URLs associated with comments 3 Login using account 10 Create account
36
Sample App Review
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.