Deep Dive Into The Framework

Vijay Menon, Organizer

https://javascriptla.net

Today's Agenda

  • High Level Overview
  • Simple App Build
  • Exploring Angular Features
  • Advanced
  • Q & A (including FAQs)

High Level

 

Angular is a JavaScript framework that:

  • Helps us speed up web development
  • Declarative not imperative programming
  • Allows us to organize our code into reusable components
  • Follows MVC design pattern
  • Gives our code "super powers" from Google
  • Can work with common backend (e.g. Java, PHP, Ruby, Python, Node.js)

 

Angular is currently in version 8, and documentation is available at https://www.angular.io 

Why Angular?

vs something else (e.g. React, Vue, JQuery, Wordpress)?

  • React, Vue are concerned with the V in MVC, hence more tooling required to "stitch" together parts (e.g. Redux, MobX)
  • JQuery is imperative, meaning you have to define all the controls back and forth between your website and the server (no MVC to help)
  • Wordpress is meant for blogging, not really lightweight web apps, and is mainly server-side PHP (hence lose benefit of dynamic JS/AJAX)
  • Ultimately, we give up control of writing our own custom code for the benefit of using something battle tested by the community that can solve lots of different business cases; and widen our perspective on how to approach challenges.

Why NOT use Angular?

  • Google products sometimes are in "beta"
    • Could be dropped or completely rewritten (aka Angular 1, 2, ... 8)
    • Google products usually compete with each other (Angular vs Dart vs Go vs whatever)
  • Angular is HARD
    • Angular is FAR more complex than writing your own HTML/CSS/JS that just works
  • You don't have the time/money to "keep learning" 
  • Sometimes just way easier to write something vanilla (if doesn't need to scale)
  • You are a conspiracy theorist

Simple App Build

The CLI Tool

  • What is a CLI?
    • Command Line Interface 
    • Essentially a tool to help you rapidly scaffold tedious things like building files, folders, views, installing dependencies, writing unit tests, deploying code to remote servers, etc -- completely depends on the tool
    • There are many CLIs out there

 

  • The Angular CLI
    • Helps us scaffold new project files and folders
    • Easily helps us create new modules, components, test files, more -- much more tedious in previous Angular versions
    • Builds everything we need so we can view our work and edit it almost in real time (includes webpack, hot module reloading, babel, etc) -- compare to getting started with React
    • Allows us to build, minify and push our code to a production server quickly and easily

Getting Setup

$ npm install -g @angular/cli

Here's how to get the latest CLI from Angular on your computer

 

Make sure you have Node Version 8.9 or HIGHER!

$ ng new myProject
$ cd myProject
$ ng serve --open

Starts downloading and creating all the files and folders you need to run Angular out of the box.  After running ng serve, you should see your browser open to this project folder's start page.

 

Let's Play Around W/Some Demos via Angular.io

Diving Into Angular Features

Here's What You Should Know

  • TypeScript
  • Modules
  • Components
  • Directives, Data Binding, Pipes
  • Services & Dependency Injection
  • Observables / rxjs
  • Routing

Try saying all of the above 5x fast!

TypeScript

  • A more "verbose" way of writing your JavaScript, as defined by "types"

 

  • JavaScript's built in type inference becomes a problem when programmers want to "port" code from one codebase to another.
    • If we stop caring about types, it could lead to bugs / errors between different programming languages
    • TypeScript aims to help solve this problem by forcing us to think more carefully about what we define in terms of variables, objects, classes and more.

 

  • TypeScript is the preferred way to write code in Angular; the good news is it's relatively easy to learn the syntax.  (Though there are gotchas).
    • It is compatible with ES6 syntax.

Get TypeScript

$ npm install -g typescript

$ touch myTypeScript.ts

$ echo "console.log('Hello World');" > myTypeScript.ts

$ tsc myTypeScript.ts

$ node myTypeScript.js

Interested in more on TypeScript?

Check out my blog post at:

https://javascriptla.net/blog/intro-to-typescript/

Modules

  • What is a module?
    • Code we can add to a project and start using (with the expectation it won't break additional code we write)

 

  • In Angular, we have ngModules:
    • Similar to JavaScript modules, however, ngModules control the flow of how things work together in Angular
    • @NgModule is a decorator we pass in JSON meta data to initialize our Angular app with; we can have additional ngModules that interact with our "root" module
    • ngModules differ from JavaScript modules in that they are designed to work with declarables (directives, components, Angular classes); they aren't meant to work with any other kind of JavaScript or 3rd party libraries

NgModule Syntax

/* These are JavaScript import statements. Angular doesn’t know anything about these. */
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';

/* The @NgModule decorator lets Angular know that this is an NgModule. */
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [     /* These are NgModule imports. */
    BrowserModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Components

  • Components help define the overall UI/UX in Angular (view logic)
  • Using the Angular CLI, we can generate a new component:
    • ng generate component YOUR_COMPONENT_HERE
      • Component.ts file
      • Component.html file
      • Component.css file
    • The component.ts file is where all our view logic goes (if you remember Angular 1, this is like the ViewController)
    • The component.html and component.css files are where you can template and style your app (and use Angular directives)

 

  • Components must be marked by a @Component decorator in order for Angular to register it
    • The @Component decorator tells Angular what templates, css,  selectors, and services to associate with said component

Component Syntax

import { Component } from '@angular/core';

import { products } from '../products';

@Component({
  selector: 'app-product-list',
  templateUrl: './product-list.component.html',
  styleUrls: ['./product-list.component.css']
})
export class ProductListComponent {
  products = products;

  share() {
    window.alert('The product has been shared!');
  }
  
  hello() {
    window.alert("A failed economy");
  }
  onNotify(){ 
    window.alert('You will be notified when the product goes on sale!');
  }
}


/*
Copyright Google LLC. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
*/

component.ts file

product-list.component.ts

Component Syntax

<h2>Products</h2>

<div *ngFor="let product of products; index as productId">

  <h3> 
    <a [title]="product.name + ' details'" [routerLink]="['/products', productId]">
      {{ product.name }} 
      </a>
  </h3>
...

component.html file (template)

product-alerts.component.html

button {
  background: rgb(245, 91, 186);
}

component.css file

product-alerts.component.css

Directives, Data Binding, Pipes

  • Directives help us interact and modify our HTML elements
    • There are three main types of directives in Angular:
      • Template directives (aka Components)
      • Structural directives - for adding, replacing, removing elements in the DOM
        • *ngIf, *ngFor 
      • Attribute directives - manipulating an existing element (e.g. element style)
        • [class], (click)

 

  • Data binding allows us to update data between Models and Views on events / changes in the DOM
    • Event binding (on user inputs)
    • Property binding (data interpolated from your application data)
    • Angular supports one way and two way data-binding

 

  • Pipes: You can pipe data through special functions in your HTML
    •  (e.g. changing text to currency, formatting dates)
    • All these features together make writing HTML more fun, and feel like something beyond just HTML5; possibly HTML6 or 7!

Examples

Directive Type Example Use
Structural *ngIf="hero.name" Hide / Show el
Attribute [(ngModel)]="hero.name" two way binding on a compoent property
Pipe <p>Today is {{today | date }}</p>  
 
Format today to the date

Services & Dependency Injection (DI)

  • Services are any pieces of code (modular) that are not directly tied towards the UI / UX of any component
    • (e.g. they can be abstracted to be used widespread through an app OR multiple apps; like getting data from a server via HTTP)
  • A service typically should do one thing, and do it WELL (think pure function)

 

  • Component = User Experience
  • Service = Abstracted Code To Augment a Component / Application
    • Examples of services:
      • Validation services (to prevent bad data)
      • Logging services (to record data)
      • HTTP services (AJAX)

 

  • Dependency Injection (DI)
    • The act of delegating a service to a component (components)
    • You can also inject functions, values into components 
    • You "inject" services via the @Injectable() decorator using metadata

Example

export class HeroListComponent implements OnInit {
  heroes: Hero[];
  selectedHero: Hero;

  constructor(private service: HeroService) { }

  ngOnInit() {
    this.heroes = this.service.getHeroes();
  }

  selectHero(hero: Hero) { this.selectedHero = hero; }
}

Implement a Service in a component

Observables / rxjs

  • Observables allow us to "subscribe" to different types of events occurring in our application
    • For example asynchronous JavaScript (aka AJAX)
      • You don't get the data immediately, you have to "wait" for it
      • Observables can "subscribe" to an AJAX call and on completion, we can return the Observable (similar to returning a Promise)

 

  • rxjs - A library of prebuilt Observables we can include with our Angular app
    • Some of the popular rxjs observables include:
      • Promise observables
      • Timers
      • DOM Events
      • AJAX 
    • rxjs = Reactive Extensions for JavaScript

 

rxjs and Observables are a course in themselves!  

Routing

  • Allows our app to work with the browser URL and map View Components to different paths we define.

 

  • Router is a service provided by Angular, but does not belong to Angular Core (it's separate and must be imported into an application)

Movie Search App

  • Let's build a movie search app together using Angular.  
    • A lot of these topics we talked about will start to become more clear with an example
  • If you remember my presentation from 2015, I did this app using React; let's take that example and see how it's done in Angular -- We might even augment that app (time permit)!

 

  • Basic needs of our App:
    • Search box (to search for titles)
    • Table View showing our results
      • Individual listings of each result 

Movie App

Search Bar

MovieList

MovieListing

Final Result Available on Firebase

Want to Learn ES6?

Check out my video course via https://www.hackbudy.com.  

 

You'll get over 8 hours of video training, plus:

  • Free copy of Survive Programming: A Guide to ES6 written by me
  • Invite to private Discord channel to answer your common Q&As
  • Private group session with me to further learn about TypeScript and new features of ES10

 

Act NOW! Use code SUMMER-PREVIEW to save 70% - after August ends, deal is gone!

Thanks for coming!

Support the group, get a T-shirt (or books, videos)!

Visit https://javascriptla.net and click "Shop"

See You At The Next Meetup!

Get on the mailing list at: https://javascriptla.net

Angular Deep Dive

By JavaScriptLA

Angular Deep Dive

  • 3,172