Angular

A Modern Frontend Web Framework

Modules

Angular modules are a way to group together a cohesive unit of  functionality for a domain in the app.  They can contain components, service providers or other libraries.

Angular modules are composable. 

 

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
@NgModule({
  imports:      [ BrowserModule ],
  providers:    [ Logger ],
  declarations: [ AppComponent ],
  exports:      [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

Example Module

Components

A component controls a patch on the screen.  They contain their own data logic, scoped css, and html template.

Components can be nested, creating a parent child relationship.

@Component({
  selector:    'app-hero-list',
  templateUrl: './hero-list.component.html',
  stylesUrl: './hero-list.component.css',
  providers:  [ HeroService ]
})

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

Example Component

 

import { Component } from '@angular/core';
 
@Component({
  selector: 'app-root',
  template: `
    <h1>{{title}}</h1>
    <h2>My favorite hero is: {{myHero}}</h2>
    `
})
export class AppComponent {
  title = 'Tour of Heroes';
  myHero = 'Windstorm';
}

Displaying Data

  <h1>{{title}}</h1>
  <h2>My favorite hero is: {{myHero}}</h2>
  <p>Heroes:</p>
  <ul>
    <li *ngFor="let hero of heroes">
      {{ hero }}
    </li>
  </ul>

Rendering Lists with *ngFor

<p *ngIf="true">
  Expression is true and ngIf is true.
  This paragraph is in the DOM.
</p>
<p *ngIf="false">
  Expression is false and ngIf is false.
  This paragraph is not in the DOM.
</p>

Conditional Rendering with *ngIf

<p>The hero's birthday is {{ birthday | date }}</p>

Pipes

Some built in pipes provided by Angular are:

  1. date
  2. uppercase
  3. lowercase
  4. currency
  5. percent

 

Services

A service is a broad category encompassing any value, function, or feature that an app needs.

 

A service is typically a class with a narrow, well-defined purpose. It should do something specific and do it well.

 

Services can be injected into components.

import { Injectable } from '@angular/core';
import { HeroModule } from './hero.module';
import { HEROES }     from './mock-heroes';

@Injectable({

  providedIn: HeroModule,
})
export class HeroService {
  getHeroes() { return HEROES; }
}

Example Service

Dependency Injection

Angular uses dependency injection for different services and providers to talk to each other, and to components.

import { Injectable } from '@angular/core';
import { HeroModule } from './hero.module';
import { HEROES }     from './mock-heroes';

@Injectable({
  // we declare that this service should be created
  // by any injector that includes HeroModule.

  providedIn: HeroModule,
})
export class HeroService {
  getHeroes() { return HEROES; }
}

Making a service Injectable

import { Component }   from '@angular/core';
import { Hero }        from './hero';
import { HeroService } from './hero.service';
 
@Component({
  selector: 'app-hero-list',
  template: `
    <div *ngFor="let hero of heroes">
      {{hero.id}} - {{hero.name}}
    </div>
  `
})
export class HeroListComponent {
  heroes: Hero[];
 
  constructor(heroService: HeroService) {
    this.heroes = heroService.getHeroes();
  }
}

Injecting into Component

Routing and Navigation

Routing allows navigation from one component view to another.

Your browser's url bar is intercepted to display specific components  in the SPA instead of making a get request to a server.

const appRoutes: Routes = [
  { path: 'crisis-center', component: CrisisListComponent },
  { 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,
      { enableTracing: true } // <-- debugging purposes only
    )
    // other imports here
  ],
  ...
})
export class AppModule { }

Route Definitions

  <h1>Angular Router</h1>
  <nav>
    <a routerLink="/crisis-center" routerLinkActive="active">Crisis Center</a>
    <a routerLink="/heroes" routerLinkActive="active">Heroes</a>
  </nav>
  <router-outlet></router-outlet>

Displaying Route Components

The components in the router are displayed via a custom html tag called <router-outlet>.  This goes in your html template.

 

routerLink is how can create links to navigate to your components defined in the router module

HTTP Calls from the Client

Angular's HttpClient module is a wrapper around the browser's native XMLHttpRequest object.

 

Benefits of the HttpClient Module include:

  1. Testability features
  2. Typed request & response objects
  3. Request and Response interception
  4. Observable API's
  5. Streamlined error handling
import { NgModule }         from '@angular/core';
import { BrowserModule }    from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  imports: [
    BrowserModule,
    // import HttpClientModule after BrowserModule.
    HttpClientModule,
  ],
  declarations: [
    AppComponent,
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule {}

Setup

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class ConfigService {
  constructor(private http: HttpClient) { }
}

Injecting HttpClient into a Service

# config.component.ts

showConfig() {
  this.configService.getConfig()
    .subscribe((data: Config) => this.config = {
        heroesUrl: data['heroesUrl'],
        textfile:  data['textfile']
    });
}

Consuming HttpClient calls with Observables

# config.service.ts

configUrl = 'assets/config.json';

getConfig() {
  return this.http.get(this.configUrl);
}

Turning Observables to Promises

# config.component.ts

showConfig() {
  this.configService.getConfig()
    .toPromise()
    .then((data: Config) => this.config = {
        heroesUrl: data['heroesUrl'],
        textfile:  data['textfile']
    })
}

Resources

Angular

By DevLeague Coding Bootcamp

Angular

A Modern Frontend Framework

  • 1,411