Skip to content

Instantly share code, notes, and snippets.

@brandonroberts
Last active May 7, 2021 08:12
Show Gist options
  • Save brandonroberts/a44634f01413dc6bea53a5adfe97c66d to your computer and use it in GitHub Desktop.
Save brandonroberts/a44634f01413dc6bea53a5adfe97c66d to your computer and use it in GitHub Desktop.
Component Router (New) snippets

Snippets for workshop

Step 1 - Home Route

<base href="/">

'@angular/router':                   { main: 'index.js', defaultExtension: 'js' },

import {ROUTER_PROVIDERS} from '@angular/router';

ROUTER_PROVIDERS,

import {Routes, ROUTER_DIRECTIVES, Router} from '@angular/router';

ROUTER_DIRECTIVES

<router-outlet></router-outlet>

@Routes([
  {
    path: '/',
    component: HomeComponent
  }
])

constructor(router: Router) {}

Step 2 - Nested Route

{
  path: '/blog',
  component: BlogPostsComponent
}
  
import {Routes, ROUTER_DIRECTIVES} from '@angular/router';

ROUTER_DIRECTIVES
  
@Routes([
  {
    path: '/',
    component: PostListComponent
  },
  {
    path: '/posts/:id',
    component: BlogPostComponent
  }
])  
  
<router-outlet></router-outlet>

Step 3 - Navigation

[routerLink]="['/']"

[routerLink]="['/blog']"

import {ROUTER_DIRECTIVES} from '@angular/router';

ROUTER_DIRECTIVES

[routerLink]="['posts', post.id]"

router-link-active class??

Step 3b - Navigating imperatively

import {Router} from '@angular/router';

, public router: Router

this.router.navigate(['../blog']);

Step 4 Route Segment

, OnActivate, RouteSegment, RouteTree

implements OnActivate

routerOnActivate(
  current: RouteSegment,
  prev?: RouteSegment,
  currTree?: RouteTree,
  prevTree?: RouteTree
) {
  let id =+ current.getParam('id');
  this.getPost(id);
}

Step 5 Location Strategy

import {provide} from '@angular/core';
import {LocationStrategy,
        HashLocationStrategy} from '@angular/common';

provide(LocationStrategy, {
    useClass: HashLocationStrategy })

Step 6 Lifecycle Hooks

  import {CanDeactivate, RouteTree} from '@angular/router';

 , CanDeactivate

 routerCanDeactivate(current: RouteTree, prev: RouteTree) {
   return Promise.resolve(window.confirm('Are you sure you want to leave?'));
 }

Step 7 Lazy Loading

Temporary - In index.html change node_modules/@angular to http://npmcdn.com/ngconf-router-build 



import {provide,
        ComponentResolver,
        SystemJsComponentResolver} from '@angular/core';
import {RuntimeCompiler} from '@angular/compiler';

provide(ComponentResolver, {
  useFactory: (compiler) => new SystemJsComponentResolver(compiler),
  deps: [RuntimeCompiler]}
),

default BlogPostsComponent

'app/blog-posts.component'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment