import { Component, Inject, OnInit } from '@angular/core';
import { Router, ROUTER_DIRECTIVES } from '@angular/router';
import { DialogService } from './dialog.service';
import { HeroService } from './heroes/hero.service';
@Component({
selector: 'my-app',
template: `
<h1 class="title">Component Router</h1>
<nav>
<a [routerLinkActive]="['is-active']" [routerLink]="['/']">Home</a>
<a [routerLinkActive]="['is-active']" [routerLink]="['/crisis-center']">Crisis Center</a>
<a [routerLinkActive]="['is-active']" [routerLink]="['/heroes']">Heroes</a>
</nav>
<router-outlet></router-outlet>
`,
styles: [
'.is-active { background-color: #607D8B; color: #fff; }',
],
providers: [
HeroService,
DialogService
],
directives: [ROUTER_DIRECTIVES]
})
export class AppComponent {
constructor(
@Inject('routerSynchronizer') private sync,
private router: Router
) {}
ngOnInit() {
this.sync.connect('app', this.router);
}
}
/*
Copyright 2016 Google Inc. 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
*/
import { provideRouter, RouterConfig } from '@angular/router';
import { CrisisCenterRoutes } from './crisis-center/crisis-center.routes';
import { HeroesRoutes } from './heroes/heroes.routes';
import { LoginRoutes,
AUTH_PROVIDERS } from './login.routes';
import { HomeComponent } from './home.component.ts';
import { CanDeactivateGuard } from './interfaces';
export const routes: RouterConfig = [
{ path: '', component: HomeComponent },
...HeroesRoutes,
...LoginRoutes,
...CrisisCenterRoutes
];
export const APP_ROUTER_PROVIDERS = [
provideRouter(routes),
AUTH_PROVIDERS,
CanDeactivateGuard
];
/*
Copyright 2016 Google Inc. 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
*/
import { Injectable } from '@angular/core';
import { CanActivate,
Router,
ActivatedRouteSnapshot,
RouterStateSnapshot } from '@angular/router';
import { AuthService } from './auth.service';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(
// Not using but worth knowing about
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot
) {
if (this.authService.isLoggedIn) { return true; }
this.router.navigate(['/login']);
return false;
}
}
/*
Copyright 2016 Google Inc. 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
*/
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/delay';
@Injectable()
export class AuthService {
isLoggedIn: boolean = false;
login() {
return Observable.of(true).delay(1000).do(val => this.isLoggedIn = true);
}
logout() {
this.isLoggedIn = false;
}
}
/*
Copyright 2016 Google Inc. 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
*/
import { Component } from '@angular/core';
import { ROUTER_DIRECTIVES } from '@angular/router';
@Component({
template: `
<h3>CRISIS ADMINISTRATION</h3>
<p>Manage your crises here</p>
`,
directives: [ROUTER_DIRECTIVES]
})
export class CrisisAdminComponent { }
/*
Copyright 2016 Google Inc. 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
*/
import { Component } from '@angular/core';
import { ROUTER_DIRECTIVES } from '@angular/router';
import { CrisisService } from './crisis.service';
@Component({
template: `
<h2>CRISIS CENTER</h2>
<router-outlet></router-outlet>
`,
directives: [ROUTER_DIRECTIVES],
providers: [CrisisService]
})
export class CrisisCenterComponent { }
/*
Copyright 2016 Google Inc. 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
*/
import { RouterConfig } from '@angular/router';
import { CrisisDetailComponent } from './crisis-detail.component';
import { CrisisListComponent } from './crisis-list.component';
import { CrisisCenterComponent } from './crisis-center.component';
import { CrisisAdminComponent } from './crisis-admin.component';
import { CanDeactivateGuard } from '../interfaces';
import { AuthGuard } from '../auth.guard';
export const CrisisCenterRoutes: RouterConfig = [
{
path: '',
redirectTo: '/crisis-center',
terminal: true
},
{
path: 'crisis-center',
component: CrisisCenterComponent,
children: [
{
path: 'admin',
component: CrisisAdminComponent,
canActivate: [AuthGuard]
},
{
path: ':id',
component: CrisisDetailComponent,
canDeactivate: [CanDeactivateGuard]
},
{
path: '',
component: CrisisListComponent
}
]
}
];
/*
Copyright 2016 Google Inc. 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
*/
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/fromPromise';
import { Crisis, CrisisService } from './crisis.service';
import { DialogService } from '../dialog.service';
@Component({
template: `
<div *ngIf="crisis">
<h3>"{{editName}}"</h3>
<div>
<label>Id: </label>{{crisis.id}}</div>
<div>
<label>Name: </label>
<input [(ngModel)]="editName" placeholder="name"/>
</div>
<p>
<button (click)="save()">Save</button>
<button (click)="cancel()">Cancel</button>
</p>
</div>
`,
styles: ['input {width: 20em}']
})
export class CrisisDetailComponent implements OnInit, OnDestroy {
crisis: Crisis;
editName: string;
private sub: any;
constructor(
private service: CrisisService,
private route: ActivatedRoute,
private router: Router,
private dialogService: DialogService
) { }
ngOnInit() {
this.sub = this.route
.params
.subscribe(params => {
let id = +params['id'];
this.service.getCrisis(id)
.then(crisis => {
if (crisis) {
this.editName = crisis.name;
this.crisis = crisis;
} else { // id not found
this.gotoCrises();
}
});
});
}
ngOnDestroy() {
if (this.sub) {
this.sub.unsubscribe();
}
}
cancel() {
this.gotoCrises();
}
save() {
this.crisis.name = this.editName;
this.gotoCrises();
}
canDeactivate(): Observable<boolean> | boolean {
// Allow synchronous navigation (`true`) if no crisis or the crisis is unchanged
if (!this.crisis || this.crisis.name === this.editName) {
return true;
}
// Otherwise ask the user with the dialog service and return its
// promise which resolves to true or false when the user decides
let p = this.dialogService.confirm('Discard changes?');
let o = Observable.fromPromise(p);
return o;
}
gotoCrises() {
let crisisId = this.crisis ? this.crisis.id : null;
// Pass along the hero id if available
// so that the CrisisListComponent can select that hero.
// Add a totally useless `foo` parameter for kicks.
// Absolute link
this.router.navigate(['/crisis-center', {id: crisisId, foo: 'foo'}]);
}
}
/*
Copyright 2016 Google Inc. 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
*/
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { Crisis, CrisisService } from './crisis.service';
@Component({
template: `
<ul class="items">
<li *ngFor="let crisis of crises"
[class.selected]="isSelected(crisis)"
(click)="onSelect(crisis)">
<span class="badge">{{crisis.id}}</span> {{crisis.name}}
</li>
</ul>
`,
})
export class CrisisListComponent implements OnInit, OnDestroy {
crises: Crisis[];
private selectedId: number;
private sub: any;
constructor(
private service: CrisisService,
private route: ActivatedRoute,
private router: Router) { }
isSelected(crisis: Crisis) { return crisis.id === this.selectedId; }
ngOnInit() {
this.sub = this.route
.params
.subscribe(params => {
this.selectedId = +params['id'];
this.service.getCrises()
.then(crises => this.crises = crises);
});
}
ngOnDestroy() {
if (this.sub) {
//this.sub.unsubscribe();
}
}
onSelect(crisis: Crisis) {
// Navigate with Absolute link
this.router.navigate(['/crisis-center', crisis.id]);
}
}
/*
Copyright 2016 Google Inc. 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
*/
export class Crisis {
constructor(public id: number, public name: string) { }
}
const CRISES = [
new Crisis(1, 'Dragon Burning Cities'),
new Crisis(2, 'Sky Rains Great White Sharks'),
new Crisis(3, 'Giant Asteroid Heading For Earth'),
new Crisis(4, 'Procrastinators Meeting Delayed Again'),
];
let crisesPromise = Promise.resolve(CRISES);
import { Injectable } from '@angular/core';
@Injectable()
export class CrisisService {
static nextCrisisId = 100;
getCrises() { return crisesPromise; }
getCrisis(id: number | string) {
return crisesPromise
.then(crises => crises.filter(c => c.id === +id)[0]);
}
addCrisis(name: string) {
name = name.trim();
if (name) {
let crisis = new Crisis(CrisisService.nextCrisisId++, name);
crisesPromise.then(crises => crises.push(crisis));
}
}
}
/*
Copyright 2016 Google Inc. 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
*/
import { Injectable } from '@angular/core';
/**
* Async modal dialog service
* DialogService makes this app easier to test by faking this service.
* TODO: better modal implementation that doesn't use window.confirm
*/
@Injectable()
export class DialogService {
/**
* Ask user to confirm an action. `message` explains the action and choices.
* Returns promise resolving to `true`=confirm or `false`=cancel
*/
confirm(message?: string) {
return new Promise<boolean>(resolve => {
return resolve(window.confirm(message || 'Is it OK?'));
});
};
}
/*
Copyright 2016 Google Inc. 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
*/
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { Hero, HeroService } from './hero.service';
@Component({
template: `
<h2>HEROES</h2>
<div *ngIf="hero">
<h3>"{{hero.name}}"</h3>
<div>
<label>Id: </label>{{hero.id}}</div>
<div>
<label>Name: </label>
<input [(ngModel)]="hero.name" placeholder="name"/>
</div>
<p>
<button (click)="gotoHeroes()">Back</button>
</p>
</div>
`,
})
export class HeroDetailComponent implements OnInit, OnDestroy {
hero: Hero;
private sub: any;
constructor(
private route: ActivatedRoute,
private router: Router,
private service: HeroService) {}
ngOnInit() {
this.sub = this.route.params.subscribe(params => {
let id = +params['id']; // (+) converts string 'id' to a number
this.service.getHero(id).then(hero => this.hero = hero);
});
}
ngOnDestroy() {
this.sub.unsubscribe();
}
gotoHeroes() {
let heroId = this.hero ? this.hero.id : null;
// Pass along the hero id if available
// so that the HeroList component can select that hero.
this.router.navigate(['/heroes'], { queryParams: { id: heroId, foo: 'foo' } });
}
}
/*
Copyright 2016 Google Inc. 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
*/
// TODO SOMEDAY: Feature Componetized like CrisisCenter
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Router } from '@angular/router';
import { Hero, HeroService } from './hero.service';
@Component({
template: `
<h2>HEROES</h2>
<ul class="items">
<li *ngFor="let hero of heroes"
[class.selected]="isSelected(hero)"
(click)="onSelect(hero)">
<span class="badge">{{hero.id}}</span> {{hero.name}}
</li>
</ul>
`
})
export class HeroListComponent implements OnInit, OnDestroy {
heroes: Hero[];
private selectedId: number;
private sub: any;
constructor(
private service: HeroService,
private router: Router) {}
ngOnInit() {
this.sub = this.router
.routerState
.queryParams
.subscribe(params => {
this.selectedId = +params['id'];
this.service.getHeroes()
.then(heroes => this.heroes = heroes);
});
}
ngOnDestroy() {
//this.sub.unsubscribe();
}
isSelected(hero: Hero) { return hero.id === this.selectedId; }
onSelect(hero: Hero) {
this.router.navigate(['/hero', hero.id]);
}
}
/*
Copyright 2016 Google Inc. 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
*/
import { Injectable } from '@angular/core';
export class Hero {
constructor(public id: number, public name: string) { }
}
let HEROES = [
new Hero(11, 'Mr. Nice'),
new Hero(12, 'Narco'),
new Hero(13, 'Bombasto'),
new Hero(14, 'Celeritas'),
new Hero(15, 'Magneta'),
new Hero(16, 'RubberMan')
];
let heroesPromise = Promise.resolve(HEROES);
@Injectable()
export class HeroService {
getHeroes() { return heroesPromise; }
getHero(id: number | string) {
return heroesPromise
.then(heroes => heroes.filter(h => h.id === +id)[0]);
}
}
/*
Copyright 2016 Google Inc. 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
*/
import { RouterConfig } from '@angular/router';
import { HeroListComponent } from './hero-list.component';
import { HeroDetailComponent } from './hero-detail.component';
export const HeroesRoutes: RouterConfig = [
{ path: 'heroes', component: HeroListComponent },
{ path: 'hero/:id', component: HeroDetailComponent }
];
/*
Copyright 2016 Google Inc. 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
*/
import { CanDeactivate } from '@angular/router';
import { Observable } from 'rxjs/Observable';
export interface CanComponentDeactivate {
canDeactivate: () => boolean | Observable<boolean>;
}
export class CanDeactivateGuard implements CanDeactivate<CanComponentDeactivate> {
canDeactivate(component: CanComponentDeactivate): Observable<boolean> | boolean {
return component.canDeactivate ? component.canDeactivate() : true;
}
}
/*
Copyright 2016 Google Inc. 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
*/
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { AuthService } from './auth.service';
@Component({
template: `
<h2>LOGIN</h2>
<p>{{message}}</p>
<p>
<button (click)="login()" *ngIf="!authService.isLoggedIn">Login</button>
<button (click)="logout()" *ngIf="authService.isLoggedIn">Logout</button>
</p>`
})
export class LoginComponent {
message: string;
constructor(public authService: AuthService, public router: Router) {
this.setMessage();
}
setMessage() {
this.message = 'Logged ' + (this.authService.isLoggedIn ? 'in' : 'out');
}
login() {
this.message = 'Trying to log in ...';
this.authService.login().subscribe(() => {
this.setMessage();
if (this.authService.isLoggedIn) {
// Todo: capture where the user was going and nav there.
// Meanwhile redirect the user to the crisis admin
this.router.navigate(['/crisis-center/admin']);
}
});
}
logout() {
this.authService.logout();
this.setMessage();
}
}
/*
Copyright 2016 Google Inc. 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
*/
import { AuthGuard } from './auth.guard';
import { AuthService } from './auth.service';
import { LoginComponent } from './login.component';
export const LoginRoutes = [
{ path: 'login', component: LoginComponent }
];
export const AUTH_PROVIDERS = [AuthGuard, AuthService];
/*
Copyright 2016 Google Inc. 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
*/
// main entry point
import { provide } from '@angular/core';
import { bootstrap } from '@angular/platform-browser-dynamic';
import { AppComponent } from './app.component';
import { NavComponent } from './nav.component';
import { APP_ROUTER_PROVIDERS } from './app.routes';
import { NAV_ROUTER_PROVIDERS } from './nav.routes';
import { RouterSynchronizer } from './router-synchronizer.ts';
const ROUTER_SYNCHRONIZER_PROVIDER = provide('routerSynchronizer', {
useValue: new RouterSynchronizer(),
});
bootstrap(AppComponent, [
APP_ROUTER_PROVIDERS,
ROUTER_SYNCHRONIZER_PROVIDER,
])
.catch(err => console.error(err));
bootstrap(NavComponent, [
NAV_ROUTER_PROVIDERS,
ROUTER_SYNCHRONIZER_PROVIDER,
])
.catch(err => console.error(err));
/*
Copyright 2016 Google Inc. 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
*/
/* Master Styles */
h1 {
color: #369;
font-family: Arial, Helvetica, sans-serif;
font-size: 250%;
}
h2, h3 {
color: #444;
font-family: Arial, Helvetica, sans-serif;
font-weight: lighter;
}
body {
margin: 2em;
}
body, input[text], button {
color: #888;
font-family: Cambria, Georgia;
}
a {
cursor: pointer;
cursor: hand;
}
button {
font-family: Arial;
background-color: #eee;
border: none;
padding: 5px 10px;
border-radius: 4px;
cursor: pointer;
cursor: hand;
}
button:hover {
background-color: #cfd8dc;
}
button:disabled {
background-color: #eee;
color: #aaa;
cursor: auto;
}
/* Navigation link styles */
nav a {
padding: 5px 10px;
text-decoration: none;
margin-top: 10px;
display: inline-block;
background-color: #eee;
border-radius: 4px;
}
nav a:visited, a:link {
color: #607D8B;
}
nav a:hover {
color: #039be5;
background-color: #CFD8DC;
}
nav a.router-link-active {
color: #039be5;
}
/* items class */
.items {
margin: 0 0 2em 0;
list-style-type: none;
padding: 0;
width: 24em;
}
.items li {
cursor: pointer;
position: relative;
left: 0;
background-color: #EEE;
margin: .5em;
padding: .3em 0;
height: 1.6em;
border-radius: 4px;
}
.items li:hover {
color: #607D8B;
background-color: #DDD;
left: .1em;
}
.items li.selected:hover {
background-color: #BBD8DC;
color: white;
}
.items .text {
position: relative;
top: -3px;
}
.items {
margin: 0 0 2em 0;
list-style-type: none;
padding: 0;
width: 24em;
}
.items li {
cursor: pointer;
position: relative;
left: 0;
background-color: #EEE;
margin: .5em;
padding: .3em 0;
height: 1.6em;
border-radius: 4px;
}
.items li:hover {
color: #607D8B;
background-color: #DDD;
left: .1em;
}
.items li.selected {
background-color: #CFD8DC;
color: white;
}
.items li.selected:hover {
background-color: #BBD8DC;
}
.items .text {
position: relative;
top: -3px;
}
.items .badge {
display: inline-block;
font-size: small;
color: white;
padding: 0.8em 0.7em 0 0.7em;
background-color: #607D8B;
line-height: 1em;
position: relative;
left: -1px;
top: -4px;
height: 1.8em;
margin-right: .8em;
border-radius: 4px 0 0 4px;
}
/* everywhere else */
* {
font-family: Arial, Helvetica, sans-serif;
}
/*
Copyright 2016 Google Inc. 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
*/
<!DOCTYPE html>
<html>
<html>
<head>
<!-- Set the base href -->
<script>document.write('<base href="' + document.location + '" />');</script>
<title>Router Sample</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
<!-- Polyfill(s) for older browsers -->
<script src="https://npmcdn.com/core-js/client/shim.min.js"></script>
<script src="https://npmcdn.com/zone.js@0.6.12?main=browser"></script>
<script src="https://npmcdn.com/reflect-metadata@0.1.3"></script>
<script src="https://npmcdn.com/systemjs@0.19.27/dist/system.src.js"></script>
<script src="systemjs.config.js"></script>
<script>
System.import('app')
.catch(function(err){ console.error(err); });
</script>
</head>
<body>
<nav-component></nav-component>
<my-app>loading...</my-app>
</body>
</html>
<!--
Copyright 2016 Google Inc. 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
-->
/**
* PLUNKER VERSION (based on systemjs.config.js in angular.io)
* System configuration for Angular 2 samples
* Adjust as necessary for your application needs.
*/
(function(global) {
var ngVer = '@2.0.0-rc.3'; // lock in the angular package version; do not let it float to current!
var routerVer = '@3.0.0-alpha.7'; // lock router version
var formsVer = '@0.1.1'; // lock forms version
//map tells the System loader where to look for things
var map = {
'app': 'app',
'@angular': 'https://npmcdn.com/@angular', // sufficient if we didn't pin the version
'@angular/router': 'https://npmcdn.com/@angular/router' + routerVer,
'@angular/forms': 'https://npmcdn.com/@angular/forms' + formsVer,
'angular2-in-memory-web-api': 'https://npmcdn.com/angular2-in-memory-web-api', // get latest
'rxjs': 'https://npmcdn.com/rxjs@5.0.0-beta.6',
'ts': 'https://npmcdn.com/plugin-typescript@4.0.10/lib/plugin.js',
'typescript': 'https://npmcdn.com/typescript@1.9.0-dev.20160409/lib/typescript.js',
};
//packages tells the System loader how to load when no filename and/or no extension
var packages = {
'app': { main: 'main.ts', defaultExtension: 'ts' },
'rxjs': { defaultExtension: 'js' },
'angular2-in-memory-web-api': { main: 'index.js', defaultExtension: 'js' },
};
var ngPackageNames = [
'common',
'compiler',
'core',
'http',
'platform-browser',
'platform-browser-dynamic',
'router-deprecated',
'upgrade',
];
// Add map entries for each angular package
// only because we're pinning the version with `ngVer`.
ngPackageNames.forEach(function(pkgName) {
map['@angular/'+pkgName] = 'https://npmcdn.com/@angular/' + pkgName + ngVer;
});
// Add package entries for angular packages
ngPackageNames.forEach(function(pkgName) {
// Bundled (~40 requests):
packages['@angular/'+pkgName] = { main: '/bundles/' + pkgName + '.umd.js', defaultExtension: 'js' };
// Individual files (~300 requests):
//packages['@angular/'+pkgName] = { main: 'index.js', defaultExtension: 'js' };
});
// No umd for router yet
packages['@angular/router'] = { main: 'index.js', defaultExtension: 'js' };
// Forms not on rc yet
packages['@angular/forms'] = { main: 'index.js', defaultExtension: 'js' };
var config = {
// DEMO ONLY! REAL CODE SHOULD NOT TRANSPILE IN THE BROWSER
transpiler: 'ts',
typescriptOptions: {
tsconfig: true
},
meta: {
'typescript': {
"exports": "ts"
}
},
map: map,
packages: packages
};
System.config(config);
})(this);
/*
Copyright 2016 Google Inc. 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
*/
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": false,
"noImplicitAny": true,
"suppressImplicitAnyIndexErrors": true
}
}
import { Inject } from '@angular/core';
import { NavigationEnd, Router } from '@angular/router';
interface ISubscriber {
id: string;
router: Router;
}
export class RouterSynchronizer {
private subscribers: ISubscriber[] = [];
connect(id: string, router: Router): void {
this.subscribers.push({ id, router });
this.startPublishing(id, router);
}
private startPublishing(source: string, router: Router): void {
router.events.subscribe(route => {
if (route instanceof NavigationEnd) {
this.subscribers.forEach(subscriber => {
if (subscriber.id === source || subscriber.router.url === route.urlAfterRedirects) {
// Prevent infinite loops.
return;
}
subscriber.router.navigateByUrl(route.urlAfterRedirects);
});
}
});
}
}
import { Component, Inject, OnInit } from '@angular/core';
import { Router, ROUTER_DIRECTIVES } from '@angular/router';
import { RouterSynchronizer } from './router-synchronizer';
@Component({
selector: 'nav-component',
template: `
<a [routerLinkActive]="['is-active']" [routerLink]="['/']">Home</a>
<a [routerLinkActive]="['is-active']" [routerLink]="['/crisis-center']">Crisis center</a>
<a [routerLinkActive]="['is-active']" [routerLink]="['/heroes']">Heroes</a>
<router-outlet></router-outlet>
<hr>
`,
styles: [
'.is-active { font-weight: bold; }',
],
directives: [ROUTER_DIRECTIVES],
})
export class NavComponent implements OnInit {
constructor(
@Inject('routerSynchronizer') private sync,
private router: Router
) {}
ngOnInit() {
this.sync.connect('nav', this.router);
}
}
import { RouterConfig, provideRouter } from '@angular/router';
import { NavCrisisCenterComponent } from './nav-crisis-center.component';
import { NavHeroesComponent } from './nav-heroes.component';
import { NavHomeComponent } from './nav-home.component';
const NavRoutes: RouterConfig = [
{
path: '',
component: NavHomeComponent,
},
{
path: 'crisis-center',
component: NavCrisisCenterComponent,
},
{
path: 'heroes',
component: NavHeroesComponent,
},
];
export const NAV_ROUTER_PROVIDERS = [
provideRouter(NavRoutes),
];
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'nav-heroes',
template: `<span *ngIf="hasRunOnInit">ngOnInit has run in NavHeroesComponent</span>`,
})
export class NavHeroesComponent implements OnInit {
private hasRunOnInit: boolean;
ngOnInit() {
this.hasRunOnInit = true;
}
}
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'nav-heroes',
template: `<span *ngIf="hasRunOnInit">ngOnInit has run in NavCrisisCenterComponent</span>`,
})
export class NavCrisisCenterComponent implements OnInit {
private hasRunOnInit: boolean;
ngOnInit() {
this.hasRunOnInit = true;
}
}
import { Component } from '@angular/core';
@Component({
selector: 'home-component',
template: 'Home',
})
export class HomeComponent {}
import { Component } from '@angular/core';
@Component({
selector: 'nav-home',
template: `<span *ngIf="hasRunOnInit">ngOnInit has run in NavHomeComponent</span>`,
})
export class NavHomeComponent {
private hasRunOnInit: boolean;
ngOnInit() {
this.hasRunOnInit = true;
}
}