├── src
├── assets
│ └── .gitkeep
├── app
│ ├── home
│ │ ├── home.component.scss
│ │ ├── home.component.html
│ │ ├── home.module.ts
│ │ └── home.component.ts
│ ├── admin
│ │ ├── list
│ │ │ ├── list.component.scss
│ │ │ ├── list.component.html
│ │ │ ├── list.component.ts
│ │ │ └── list-datasource.ts
│ │ ├── confirm-dialog
│ │ │ ├── confirm-dialog.component.scss
│ │ │ ├── confirm-dialog.component.html
│ │ │ └── confirm-dialog.component.ts
│ │ ├── welcome
│ │ │ ├── welcome.component.scss
│ │ │ ├── welcome.component.html
│ │ │ └── welcome.component.ts
│ │ ├── add-user
│ │ │ ├── add-user.component.scss
│ │ │ ├── add-user.component.html
│ │ │ └── add-user.component.ts
│ │ ├── add-product
│ │ │ ├── add-product.component.scss
│ │ │ ├── add-product.component.html
│ │ │ └── add-product.component.ts
│ │ ├── admin-routing.module.ts
│ │ └── admin.module.ts
│ ├── auth
│ │ ├── save-data.interface.ts
│ │ ├── auth.service.ts
│ │ ├── auth-preload-strategy.ts
│ │ ├── load-guard.guard.ts
│ │ ├── permissions.guard.ts
│ │ ├── authentication.guard.ts
│ │ └── form-guard.guard.ts
│ ├── app.component.scss
│ ├── app.component.ts
│ ├── app.component.html
│ ├── app-routing.module.ts
│ ├── app.module.ts
│ └── app.component.spec.ts
├── environments
│ ├── environment.prod.ts
│ └── environment.ts
├── favicon.ico
├── styles.scss
├── main.ts
├── index.html
├── test.ts
└── polyfills.ts
├── .editorconfig
├── tsconfig.app.json
├── tsconfig.spec.json
├── .browserslistrc
├── .gitignore
├── tsconfig.json
├── README.md
├── package.json
├── karma.conf.js
└── angular.json
/src/assets/.gitkeep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/src/app/home/home.component.scss:
--------------------------------------------------------------------------------
1 | :host {
2 | display: block;
3 | }
4 |
--------------------------------------------------------------------------------
/src/app/home/home.component.html:
--------------------------------------------------------------------------------
1 |
Welcome to the App | Home Page
2 |
--------------------------------------------------------------------------------
/src/app/admin/list/list.component.scss:
--------------------------------------------------------------------------------
1 | .full-width-table {
2 | width: 100%;
3 | }
4 |
--------------------------------------------------------------------------------
/src/app/admin/confirm-dialog/confirm-dialog.component.scss:
--------------------------------------------------------------------------------
1 | :host {
2 | display: block;
3 | }
4 |
--------------------------------------------------------------------------------
/src/app/auth/save-data.interface.ts:
--------------------------------------------------------------------------------
1 | export interface SafeData {
2 | isDataSaved(): boolean;
3 | }
4 |
--------------------------------------------------------------------------------
/src/environments/environment.prod.ts:
--------------------------------------------------------------------------------
1 | export const environment = {
2 | production: true
3 | };
4 |
--------------------------------------------------------------------------------
/src/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DMezhenskyi/angular-router-guards-example/HEAD/src/favicon.ico
--------------------------------------------------------------------------------
/src/app/admin/welcome/welcome.component.scss:
--------------------------------------------------------------------------------
1 | :host {
2 | display: block;
3 | }
4 | .active {
5 | border: 1px solid #333;
6 | }
7 |
--------------------------------------------------------------------------------
/src/app/app.component.scss:
--------------------------------------------------------------------------------
1 | .content {
2 | padding: 20px;
3 | box-sizing: border-box;
4 | }
5 | .first-link {
6 | margin-left: 20px;
7 | }
8 | .active {
9 | border: white 1px solid;
10 | }
11 |
--------------------------------------------------------------------------------
/src/styles.scss:
--------------------------------------------------------------------------------
1 | /* You can add global styles to this file, and also import other style files */
2 |
3 | html, body { height: 100%; }
4 | body { margin: 0; font-family: Roboto, "Helvetica Neue", sans-serif; }
5 |
--------------------------------------------------------------------------------
/src/app/admin/add-user/add-user.component.scss:
--------------------------------------------------------------------------------
1 | :host {
2 | display: block;
3 | }
4 | form {
5 | max-width: 400px;
6 | display: block;
7 | margin: 0 auto;
8 | }
9 | mat-form-field {
10 | display: block;
11 | }
12 |
--------------------------------------------------------------------------------
/src/app/admin/add-product/add-product.component.scss:
--------------------------------------------------------------------------------
1 | :host {
2 | display: block;
3 | }
4 | form {
5 | max-width: 400px;
6 | display: block;
7 | margin: 0 auto;
8 | }
9 | mat-form-field {
10 | margin-left: 10px;
11 | }
12 |
--------------------------------------------------------------------------------
/src/app/app.component.ts:
--------------------------------------------------------------------------------
1 | import { Component } from '@angular/core';
2 |
3 | @Component({
4 | selector: 'app-root',
5 | templateUrl: './app.component.html',
6 | styleUrls: ['./app.component.scss']
7 | })
8 | export class AppComponent {
9 | title = 'angular-router-guards-example';
10 | }
11 |
--------------------------------------------------------------------------------
/.editorconfig:
--------------------------------------------------------------------------------
1 | # Editor configuration, see https://editorconfig.org
2 | root = true
3 |
4 | [*]
5 | charset = utf-8
6 | indent_style = space
7 | indent_size = 2
8 | insert_final_newline = true
9 | trim_trailing_whitespace = true
10 |
11 | [*.ts]
12 | quote_type = single
13 |
14 | [*.md]
15 | max_line_length = off
16 | trim_trailing_whitespace = false
17 |
--------------------------------------------------------------------------------
/src/app/home/home.module.ts:
--------------------------------------------------------------------------------
1 | import { NgModule } from '@angular/core';
2 | import { CommonModule } from '@angular/common';
3 | import { HomeComponent } from './home.component';
4 |
5 |
6 |
7 | @NgModule({
8 | declarations: [
9 | HomeComponent
10 | ],
11 | imports: [
12 | CommonModule
13 | ]
14 | })
15 | export class HomeModule { }
16 |
--------------------------------------------------------------------------------
/tsconfig.app.json:
--------------------------------------------------------------------------------
1 | /* To learn more about this file see: https://angular.io/config/tsconfig. */
2 | {
3 | "extends": "./tsconfig.json",
4 | "compilerOptions": {
5 | "outDir": "./out-tsc/app",
6 | "types": []
7 | },
8 | "files": [
9 | "src/main.ts",
10 | "src/polyfills.ts"
11 | ],
12 | "include": [
13 | "src/**/*.d.ts"
14 | ]
15 | }
16 |
--------------------------------------------------------------------------------
/src/app/app.component.html:
--------------------------------------------------------------------------------
1 |
2 | Routing Guards
3 | Home
4 | Admin
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/src/app/auth/auth.service.ts:
--------------------------------------------------------------------------------
1 | import { Injectable } from '@angular/core';
2 | import { of } from 'rxjs';
3 | import { delay } from 'rxjs/operators';
4 |
5 | @Injectable({
6 | providedIn: 'root',
7 | })
8 | export class AuthService {
9 | constructor() {}
10 |
11 | isLoggedIn() {
12 | return of(true).pipe(delay(500));
13 | }
14 | hasPermissions() {
15 | return of(true);
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/app/admin/add-user/add-user.component.html:
--------------------------------------------------------------------------------
1 | Add new user
2 |
--------------------------------------------------------------------------------
/src/app/admin/confirm-dialog/confirm-dialog.component.html:
--------------------------------------------------------------------------------
1 | Are you sure?
2 |
3 | You data will not be saved, consider to save your form before
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/src/app/admin/add-product/add-product.component.html:
--------------------------------------------------------------------------------
1 | Add new Product
2 |
--------------------------------------------------------------------------------
/src/app/admin/confirm-dialog/confirm-dialog.component.ts:
--------------------------------------------------------------------------------
1 | import { Component, OnInit } from '@angular/core';
2 |
3 | @Component({
4 | selector: 'app-confirm-dialog',
5 | templateUrl: './confirm-dialog.component.html',
6 | styleUrls: ['./confirm-dialog.component.scss']
7 | })
8 | export class ConfirmDialogComponent implements OnInit {
9 |
10 | constructor() { }
11 |
12 | ngOnInit(): void {
13 | }
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/tsconfig.spec.json:
--------------------------------------------------------------------------------
1 | /* To learn more about this file see: https://angular.io/config/tsconfig. */
2 | {
3 | "extends": "./tsconfig.json",
4 | "compilerOptions": {
5 | "outDir": "./out-tsc/spec",
6 | "types": [
7 | "jasmine"
8 | ]
9 | },
10 | "files": [
11 | "src/test.ts",
12 | "src/polyfills.ts"
13 | ],
14 | "include": [
15 | "src/**/*.spec.ts",
16 | "src/**/*.d.ts"
17 | ]
18 | }
19 |
--------------------------------------------------------------------------------
/src/main.ts:
--------------------------------------------------------------------------------
1 | import { enableProdMode } from '@angular/core';
2 | import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
3 |
4 | import { AppModule } from './app/app.module';
5 | import { environment } from './environments/environment';
6 |
7 | if (environment.production) {
8 | enableProdMode();
9 | }
10 |
11 | platformBrowserDynamic().bootstrapModule(AppModule)
12 | .catch(err => console.error(err));
13 |
--------------------------------------------------------------------------------
/src/app/admin/welcome/welcome.component.html:
--------------------------------------------------------------------------------
1 | Secured Admin Area
2 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/src/app/home/home.component.ts:
--------------------------------------------------------------------------------
1 | import { Component, OnInit, ChangeDetectionStrategy } from '@angular/core';
2 |
3 | @Component({
4 | selector: 'app-home',
5 | templateUrl: './home.component.html',
6 | styleUrls: ['./home.component.scss'],
7 | changeDetection: ChangeDetectionStrategy.OnPush
8 | })
9 | export class HomeComponent implements OnInit {
10 |
11 | constructor() { }
12 |
13 | ngOnInit(): void {
14 | }
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/src/app/admin/welcome/welcome.component.ts:
--------------------------------------------------------------------------------
1 | import { Component, OnInit, ChangeDetectionStrategy } from '@angular/core';
2 |
3 | @Component({
4 | selector: 'app-welcome',
5 | templateUrl: './welcome.component.html',
6 | styleUrls: ['./welcome.component.scss'],
7 | changeDetection: ChangeDetectionStrategy.OnPush,
8 | })
9 | export class WelcomeComponent implements OnInit {
10 | constructor() {}
11 |
12 | ngOnInit(): void {}
13 | }
14 |
--------------------------------------------------------------------------------
/src/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | AngularRouterGuardsExample
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/src/app/auth/auth-preload-strategy.ts:
--------------------------------------------------------------------------------
1 | import { AuthService } from './auth.service';
2 | import { PreloadingStrategy, Route } from '@angular/router';
3 | import { Observable, of } from 'rxjs';
4 | import { switchMap } from 'rxjs/operators';
5 | import { Injectable } from '@angular/core';
6 |
7 | @Injectable({
8 | providedIn: 'root',
9 | })
10 | export class AuthPreloadStrategy implements PreloadingStrategy {
11 | constructor(private auth: AuthService) {}
12 |
13 | preload(route: Route, fn: () => Observable): Observable {
14 | return this.auth
15 | .isLoggedIn()
16 | .pipe(switchMap((isUserLoggedIn) => (isUserLoggedIn ? fn() : of(null))));
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/app/auth/load-guard.guard.ts:
--------------------------------------------------------------------------------
1 | import { AuthService } from './auth.service';
2 | import { Injectable } from '@angular/core';
3 | import { CanLoad, Router, UrlTree } from '@angular/router';
4 | import { Observable } from 'rxjs';
5 | import { map } from 'rxjs/operators';
6 |
7 | @Injectable({
8 | providedIn: 'root',
9 | })
10 | export class LoadGuardGuard implements CanLoad {
11 | constructor(private auth: AuthService, private router: Router) {}
12 | canLoad():
13 | | Observable
14 | | Promise
15 | | boolean
16 | | UrlTree {
17 | return this.auth
18 | .isLoggedIn()
19 | .pipe(map((isLoggedIn) => isLoggedIn || this.router.createUrlTree([''])));
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/app/app-routing.module.ts:
--------------------------------------------------------------------------------
1 | import { HomeComponent } from './home/home.component';
2 | import { NgModule } from '@angular/core';
3 | import { RouterModule, Routes } from '@angular/router';
4 | import { AuthPreloadStrategy } from './auth/auth-preload-strategy';
5 |
6 | const routes: Routes = [
7 | {
8 | path: 'admin',
9 | loadChildren: () =>
10 | import('./admin/admin.module').then((m) => m.AdminModule),
11 | },
12 | {
13 | path: '',
14 | component: HomeComponent,
15 | },
16 | ];
17 |
18 | @NgModule({
19 | imports: [
20 | RouterModule.forRoot(routes, {
21 | preloadingStrategy: AuthPreloadStrategy,
22 | }),
23 | ],
24 | exports: [RouterModule],
25 | })
26 | export class AppRoutingModule {}
27 |
--------------------------------------------------------------------------------
/src/environments/environment.ts:
--------------------------------------------------------------------------------
1 | // This file can be replaced during build by using the `fileReplacements` array.
2 | // `ng build` replaces `environment.ts` with `environment.prod.ts`.
3 | // The list of file replacements can be found in `angular.json`.
4 |
5 | export const environment = {
6 | production: false
7 | };
8 |
9 | /*
10 | * For easier debugging in development mode, you can import the following file
11 | * to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`.
12 | *
13 | * This import should be commented out in production mode because it will have a negative impact
14 | * on performance if an error is thrown.
15 | */
16 | // import 'zone.js/plugins/zone-error'; // Included with Angular CLI.
17 |
--------------------------------------------------------------------------------
/src/app/auth/permissions.guard.ts:
--------------------------------------------------------------------------------
1 | import { AuthService } from './auth.service';
2 | import { Injectable } from '@angular/core';
3 | import {
4 | ActivatedRouteSnapshot,
5 | CanActivate,
6 | CanActivateChild,
7 | RouterStateSnapshot,
8 | UrlTree,
9 | } from '@angular/router';
10 | import { Observable } from 'rxjs';
11 |
12 | @Injectable({
13 | providedIn: 'root',
14 | })
15 | export class PermissionsGuard implements CanActivateChild {
16 | constructor(private auth: AuthService) {}
17 | canActivateChild():
18 | | boolean
19 | | UrlTree
20 | | Observable
21 | | Promise {
22 | console.log('I am checking permissions....');
23 | return this.auth.hasPermissions();
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/.browserslistrc:
--------------------------------------------------------------------------------
1 | # This file is used by the build system to adjust CSS and JS output to support the specified browsers below.
2 | # For additional information regarding the format and rule options, please see:
3 | # https://github.com/browserslist/browserslist#queries
4 |
5 | # For the full list of supported browsers by the Angular framework, please see:
6 | # https://angular.io/guide/browser-support
7 |
8 | # You can see what browsers were selected by your queries by running:
9 | # npx browserslist
10 |
11 | last 1 Chrome version
12 | last 1 Firefox version
13 | last 2 Edge major versions
14 | last 2 Safari major versions
15 | last 2 iOS major versions
16 | Firefox ESR
17 | not IE 11 # Angular supports IE 11 only as an opt-in. To opt-in, remove the 'not' prefix on this line.
18 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # See http://help.github.com/ignore-files/ for more about ignoring files.
2 |
3 | # compiled output
4 | /dist
5 | /tmp
6 | /out-tsc
7 | # Only exists if Bazel was run
8 | /bazel-out
9 |
10 | # dependencies
11 | /node_modules
12 |
13 | # profiling files
14 | chrome-profiler-events*.json
15 |
16 | # IDEs and editors
17 | /.idea
18 | .project
19 | .classpath
20 | .c9/
21 | *.launch
22 | .settings/
23 | *.sublime-workspace
24 |
25 | # IDE - VSCode
26 | .vscode/*
27 | !.vscode/settings.json
28 | !.vscode/tasks.json
29 | !.vscode/launch.json
30 | !.vscode/extensions.json
31 | .history/*
32 |
33 | # misc
34 | /.sass-cache
35 | /connect.lock
36 | /coverage
37 | /libpeerconnection.log
38 | npm-debug.log
39 | yarn-error.log
40 | testem.log
41 | /typings
42 |
43 | # System Files
44 | .DS_Store
45 | Thumbs.db
46 |
--------------------------------------------------------------------------------
/src/app/admin/add-user/add-user.component.ts:
--------------------------------------------------------------------------------
1 | import { SafeData } from './../../auth/save-data.interface';
2 | import { Component, OnInit, ChangeDetectionStrategy } from '@angular/core';
3 | import { FormBuilder, FormControl, FormGroup } from '@angular/forms';
4 |
5 | @Component({
6 | selector: 'app-add-user',
7 | templateUrl: './add-user.component.html',
8 | styleUrls: ['./add-user.component.scss'],
9 | changeDetection: ChangeDetectionStrategy.OnPush,
10 | })
11 | export class AddUserComponent implements OnInit, SafeData {
12 | form: FormGroup;
13 | constructor(private fb: FormBuilder) {
14 | this.form = this.fb.group({
15 | name: new FormControl(''),
16 | email: new FormControl(''),
17 | });
18 | }
19 |
20 | ngOnInit(): void {}
21 |
22 | isDataSaved(): boolean {
23 | return !this.form.dirty;
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/test.ts:
--------------------------------------------------------------------------------
1 | // This file is required by karma.conf.js and loads recursively all the .spec and framework files
2 |
3 | import 'zone.js/testing';
4 | import { getTestBed } from '@angular/core/testing';
5 | import {
6 | BrowserDynamicTestingModule,
7 | platformBrowserDynamicTesting
8 | } from '@angular/platform-browser-dynamic/testing';
9 |
10 | declare const require: {
11 | context(path: string, deep?: boolean, filter?: RegExp): {
12 | keys(): string[];
13 | (id: string): T;
14 | };
15 | };
16 |
17 | // First, initialize the Angular testing environment.
18 | getTestBed().initTestEnvironment(
19 | BrowserDynamicTestingModule,
20 | platformBrowserDynamicTesting()
21 | );
22 | // Then we find all the tests.
23 | const context = require.context('./', true, /\.spec\.ts$/);
24 | // And load the modules.
25 | context.keys().map(context);
26 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | /* To learn more about this file see: https://angular.io/config/tsconfig. */
2 | {
3 | "compileOnSave": false,
4 | "compilerOptions": {
5 | "baseUrl": "./",
6 | "outDir": "./dist/out-tsc",
7 | "forceConsistentCasingInFileNames": true,
8 | "strict": true,
9 | "noImplicitReturns": true,
10 | "noFallthroughCasesInSwitch": true,
11 | "sourceMap": true,
12 | "declaration": false,
13 | "downlevelIteration": true,
14 | "experimentalDecorators": true,
15 | "moduleResolution": "node",
16 | "importHelpers": true,
17 | "target": "es2017",
18 | "module": "es2020",
19 | "lib": [
20 | "es2018",
21 | "dom"
22 | ]
23 | },
24 | "angularCompilerOptions": {
25 | "enableI18nLegacyMessageIdFormat": false,
26 | "strictInjectionParameters": true,
27 | "strictInputAccessModifiers": true,
28 | "strictTemplates": true
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/app/app.module.ts:
--------------------------------------------------------------------------------
1 | import { NgModule } from '@angular/core';
2 | import { BrowserModule } from '@angular/platform-browser';
3 |
4 | import { AppRoutingModule } from './app-routing.module';
5 | import { AppComponent } from './app.component';
6 | import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
7 | import { MatToolbarModule } from '@angular/material/toolbar';
8 | import { MatButtonModule } from '@angular/material/button';
9 | import { MatDialogModule } from '@angular/material/dialog';
10 | import { HomeModule } from './home/home.module';
11 |
12 | @NgModule({
13 | declarations: [AppComponent],
14 | imports: [
15 | BrowserModule,
16 | AppRoutingModule,
17 | BrowserAnimationsModule,
18 | MatToolbarModule,
19 | MatDialogModule,
20 | MatButtonModule,
21 | HomeModule,
22 | ],
23 | providers: [],
24 | bootstrap: [AppComponent],
25 | })
26 | export class AppModule {}
27 |
--------------------------------------------------------------------------------
/src/app/auth/authentication.guard.ts:
--------------------------------------------------------------------------------
1 | import { AuthService } from './auth.service';
2 | import { Injectable } from '@angular/core';
3 | import {
4 | ActivatedRouteSnapshot,
5 | CanActivate,
6 | Router,
7 | RouterStateSnapshot,
8 | UrlTree,
9 | } from '@angular/router';
10 | import { Observable } from 'rxjs';
11 | import { map } from 'rxjs/operators';
12 |
13 | @Injectable({
14 | providedIn: 'root',
15 | })
16 | export class AuthenticationGuard implements CanActivate {
17 | constructor(private auth: AuthService, private router: Router) {}
18 | canActivate(
19 | route: ActivatedRouteSnapshot,
20 | state: RouterStateSnapshot
21 | ):
22 | | Observable
23 | | Promise
24 | | boolean
25 | | UrlTree {
26 | console.log('I am checking auth...');
27 | return this.auth
28 | .isLoggedIn()
29 | .pipe(map((isLoggedIn) => isLoggedIn || this.router.createUrlTree([''])));
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/app/admin/list/list.component.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | | Id |
6 | {{row.id}} |
7 |
8 |
9 |
10 |
11 | Name |
12 | {{row.name}} |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/src/app/admin/add-product/add-product.component.ts:
--------------------------------------------------------------------------------
1 | import { Component, HostListener, OnInit } from '@angular/core';
2 | import { FormBuilder, FormControl, FormGroup } from '@angular/forms';
3 | import { SafeData } from 'src/app/auth/save-data.interface';
4 |
5 | @Component({
6 | selector: 'app-add-product',
7 | templateUrl: './add-product.component.html',
8 | styleUrls: ['./add-product.component.scss'],
9 | })
10 | export class AddProductComponent implements OnInit, SafeData {
11 | @HostListener('window:beforeunload', ['$event'])
12 | onBeforeReload(e: BeforeUnloadEvent) {
13 | e.stopPropagation();
14 | if (this.form.dirty) {
15 | return (e.returnValue = 'Are you sure you want to exit?');
16 | }
17 | return;
18 | }
19 |
20 | form: FormGroup;
21 | constructor(private fb: FormBuilder) {
22 | this.form = this.fb.group({
23 | name: new FormControl(''),
24 | quantity: new FormControl(0),
25 | });
26 | }
27 | isDataSaved(): boolean {
28 | return !this.form.dirty;
29 | }
30 |
31 | ngOnInit(): void {}
32 | }
33 |
--------------------------------------------------------------------------------
/src/app/auth/form-guard.guard.ts:
--------------------------------------------------------------------------------
1 | import { SafeData } from './save-data.interface';
2 | import { ConfirmDialogComponent } from './../admin/confirm-dialog/confirm-dialog.component';
3 | import { AddProductComponent } from './../admin/add-product/add-product.component';
4 | import { Injectable } from '@angular/core';
5 | import {
6 | ActivatedRouteSnapshot,
7 | CanDeactivate,
8 | RouterStateSnapshot,
9 | UrlTree,
10 | } from '@angular/router';
11 | import { Observable, of } from 'rxjs';
12 | import { MatDialog } from '@angular/material/dialog';
13 |
14 | @Injectable({
15 | providedIn: 'root',
16 | })
17 | export class FormGuardGuard implements CanDeactivate {
18 | constructor(private dialog: MatDialog) {}
19 | canDeactivate(
20 | component: SafeData
21 | ):
22 | | Observable
23 | | Promise
24 | | boolean
25 | | UrlTree {
26 | if (!component.isDataSaved()) {
27 | const dialogRef = this.dialog.open(ConfirmDialogComponent);
28 | return dialogRef.afterClosed();
29 | }
30 | return of(true);
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # AngularRouterGuardsExample
2 |
3 | This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 12.0.3.
4 |
5 | ## Development server
6 |
7 | Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files.
8 |
9 | ## Code scaffolding
10 |
11 | Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`.
12 |
13 | ## Build
14 |
15 | Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory.
16 |
17 | ## Running unit tests
18 |
19 | Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io).
20 |
21 | ## Running end-to-end tests
22 |
23 | Run `ng e2e` to execute the end-to-end tests via a platform of your choice. To use this command, you need to first add a package that implements end-to-end testing capabilities.
24 |
25 | ## Further help
26 |
27 | To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI Overview and Command Reference](https://angular.io/cli) page.
28 |
--------------------------------------------------------------------------------
/src/app/admin/list/list.component.ts:
--------------------------------------------------------------------------------
1 | import { AfterViewInit, Component, ViewChild, ChangeDetectionStrategy } from '@angular/core';
2 | import { MatPaginator } from '@angular/material/paginator';
3 | import { MatSort } from '@angular/material/sort';
4 | import { MatTable } from '@angular/material/table';
5 | import { ListDataSource, ListItem } from './list-datasource';
6 |
7 | @Component({
8 | selector: 'app-list',
9 | templateUrl: './list.component.html',
10 | styleUrls: ['./list.component.scss'],
11 | changeDetection: ChangeDetectionStrategy.OnPush
12 | })
13 | export class ListComponent implements AfterViewInit {
14 | @ViewChild(MatPaginator) paginator!: MatPaginator;
15 | @ViewChild(MatSort) sort!: MatSort;
16 | @ViewChild(MatTable) table!: MatTable;
17 | dataSource: ListDataSource;
18 |
19 | /** Columns displayed in the table. Columns IDs can be added, removed, or reordered. */
20 | displayedColumns = ['id', 'name'];
21 |
22 | constructor() {
23 | this.dataSource = new ListDataSource();
24 | }
25 |
26 | ngAfterViewInit(): void {
27 | this.dataSource.sort = this.sort;
28 | this.dataSource.paginator = this.paginator;
29 | this.table.dataSource = this.dataSource;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/app/app.component.spec.ts:
--------------------------------------------------------------------------------
1 | import { TestBed } from '@angular/core/testing';
2 | import { RouterTestingModule } from '@angular/router/testing';
3 | import { AppComponent } from './app.component';
4 |
5 | describe('AppComponent', () => {
6 | beforeEach(async () => {
7 | await TestBed.configureTestingModule({
8 | imports: [
9 | RouterTestingModule
10 | ],
11 | declarations: [
12 | AppComponent
13 | ],
14 | }).compileComponents();
15 | });
16 |
17 | it('should create the app', () => {
18 | const fixture = TestBed.createComponent(AppComponent);
19 | const app = fixture.componentInstance;
20 | expect(app).toBeTruthy();
21 | });
22 |
23 | it(`should have as title 'angular-router-guards-example'`, () => {
24 | const fixture = TestBed.createComponent(AppComponent);
25 | const app = fixture.componentInstance;
26 | expect(app.title).toEqual('angular-router-guards-example');
27 | });
28 |
29 | it('should render title', () => {
30 | const fixture = TestBed.createComponent(AppComponent);
31 | fixture.detectChanges();
32 | const compiled = fixture.nativeElement;
33 | expect(compiled.querySelector('.content span').textContent).toContain('angular-router-guards-example app is running!');
34 | });
35 | });
36 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "angular-router-guards-example",
3 | "version": "0.0.0",
4 | "scripts": {
5 | "ng": "ng",
6 | "start": "ng serve",
7 | "build": "ng build",
8 | "watch": "ng build --watch --configuration development",
9 | "test": "ng test"
10 | },
11 | "private": true,
12 | "dependencies": {
13 | "@angular/animations": "~12.0.3",
14 | "@angular/cdk": "^12.0.5",
15 | "@angular/common": "~12.0.3",
16 | "@angular/compiler": "~12.0.3",
17 | "@angular/core": "~12.0.3",
18 | "@angular/forms": "~12.0.3",
19 | "@angular/material": "^12.0.5",
20 | "@angular/platform-browser": "~12.0.3",
21 | "@angular/platform-browser-dynamic": "~12.0.3",
22 | "@angular/router": "~12.0.3",
23 | "rxjs": "~6.6.0",
24 | "tslib": "^2.1.0",
25 | "zone.js": "~0.11.4"
26 | },
27 | "devDependencies": {
28 | "@angular-devkit/build-angular": "~12.0.3",
29 | "@angular/cli": "~12.0.3",
30 | "@angular/compiler-cli": "~12.0.3",
31 | "@types/jasmine": "~3.6.0",
32 | "@types/node": "^12.11.1",
33 | "jasmine-core": "~3.7.0",
34 | "karma": "~6.3.0",
35 | "karma-chrome-launcher": "~3.1.0",
36 | "karma-coverage": "~2.0.3",
37 | "karma-jasmine": "~4.0.0",
38 | "karma-jasmine-html-reporter": "^1.5.0",
39 | "typescript": "~4.2.3"
40 | }
41 | }
--------------------------------------------------------------------------------
/src/app/admin/admin-routing.module.ts:
--------------------------------------------------------------------------------
1 | import { WelcomeComponent } from './welcome/welcome.component';
2 | import { NgModule } from '@angular/core';
3 | import { RouterModule, Routes } from '@angular/router';
4 | import { CommonModule } from '@angular/common';
5 | import { PermissionsGuard } from '../auth/permissions.guard';
6 | import { FormGuardGuard } from '../auth/form-guard.guard';
7 | import { AddUserComponent } from './add-user/add-user.component';
8 | import { AddProductComponent } from './add-product/add-product.component';
9 | import { ListComponent } from './list/list.component';
10 |
11 | const routes: Routes = [
12 | {
13 | path: '',
14 | component: WelcomeComponent,
15 | children: [
16 | {
17 | path: '',
18 | canActivateChild: [PermissionsGuard],
19 | children: [
20 | {
21 | path: 'add-user',
22 | canDeactivate: [FormGuardGuard],
23 | component: AddUserComponent,
24 | },
25 | {
26 | path: 'add-product',
27 | canDeactivate: [FormGuardGuard],
28 | component: AddProductComponent,
29 | },
30 | ],
31 | },
32 | { path: 'list', component: ListComponent },
33 | ],
34 | },
35 | ];
36 |
37 | @NgModule({
38 | imports: [CommonModule, RouterModule.forChild(routes)],
39 | exports: [RouterModule],
40 | })
41 | export class AdminRoutingModule {}
42 |
--------------------------------------------------------------------------------
/karma.conf.js:
--------------------------------------------------------------------------------
1 | // Karma configuration file, see link for more information
2 | // https://karma-runner.github.io/1.0/config/configuration-file.html
3 |
4 | module.exports = function (config) {
5 | config.set({
6 | basePath: '',
7 | frameworks: ['jasmine', '@angular-devkit/build-angular'],
8 | plugins: [
9 | require('karma-jasmine'),
10 | require('karma-chrome-launcher'),
11 | require('karma-jasmine-html-reporter'),
12 | require('karma-coverage'),
13 | require('@angular-devkit/build-angular/plugins/karma')
14 | ],
15 | client: {
16 | jasmine: {
17 | // you can add configuration options for Jasmine here
18 | // the possible options are listed at https://jasmine.github.io/api/edge/Configuration.html
19 | // for example, you can disable the random execution with `random: false`
20 | // or set a specific seed with `seed: 4321`
21 | },
22 | clearContext: false // leave Jasmine Spec Runner output visible in browser
23 | },
24 | jasmineHtmlReporter: {
25 | suppressAll: true // removes the duplicated traces
26 | },
27 | coverageReporter: {
28 | dir: require('path').join(__dirname, './coverage/angular-router-guards-example'),
29 | subdir: '.',
30 | reporters: [
31 | { type: 'html' },
32 | { type: 'text-summary' }
33 | ]
34 | },
35 | reporters: ['progress', 'kjhtml'],
36 | port: 9876,
37 | colors: true,
38 | logLevel: config.LOG_INFO,
39 | autoWatch: true,
40 | browsers: ['Chrome'],
41 | singleRun: false,
42 | restartOnFileChange: true
43 | });
44 | };
45 |
--------------------------------------------------------------------------------
/src/app/admin/admin.module.ts:
--------------------------------------------------------------------------------
1 | import { AdminRoutingModule } from './admin-routing.module';
2 | import { MatDialogModule } from '@angular/material/dialog';
3 | import { RouterModule } from '@angular/router';
4 | import { NgModule } from '@angular/core';
5 | import { CommonModule } from '@angular/common';
6 | import { WelcomeComponent } from './welcome/welcome.component';
7 | import { AddUserComponent } from './add-user/add-user.component';
8 | import { ReactiveFormsModule } from '@angular/forms';
9 | import { MatInputModule } from '@angular/material/input';
10 | import { MatFormFieldModule } from '@angular/material/form-field';
11 | import { MatButtonModule } from '@angular/material/button';
12 | import { AddProductComponent } from './add-product/add-product.component';
13 | import { ListComponent } from './list/list.component';
14 | import { MatTableModule } from '@angular/material/table';
15 | import { MatPaginatorModule } from '@angular/material/paginator';
16 | import { MatSortModule } from '@angular/material/sort';
17 | import { ConfirmDialogComponent } from './confirm-dialog/confirm-dialog.component';
18 |
19 | @NgModule({
20 | declarations: [
21 | WelcomeComponent,
22 | AddUserComponent,
23 | AddProductComponent,
24 | ListComponent,
25 | ConfirmDialogComponent,
26 | ],
27 | imports: [
28 | CommonModule,
29 | ReactiveFormsModule,
30 | MatInputModule,
31 | MatFormFieldModule,
32 | MatButtonModule,
33 | RouterModule,
34 | MatTableModule,
35 | MatPaginatorModule,
36 | MatSortModule,
37 | MatDialogModule,
38 | AdminRoutingModule,
39 | ],
40 | })
41 | export class AdminModule {}
42 |
--------------------------------------------------------------------------------
/src/polyfills.ts:
--------------------------------------------------------------------------------
1 | /**
2 | * This file includes polyfills needed by Angular and is loaded before the app.
3 | * You can add your own extra polyfills to this file.
4 | *
5 | * This file is divided into 2 sections:
6 | * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers.
7 | * 2. Application imports. Files imported after ZoneJS that should be loaded before your main
8 | * file.
9 | *
10 | * The current setup is for so-called "evergreen" browsers; the last versions of browsers that
11 | * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera),
12 | * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile.
13 | *
14 | * Learn more in https://angular.io/guide/browser-support
15 | */
16 |
17 | /***************************************************************************************************
18 | * BROWSER POLYFILLS
19 | */
20 |
21 | /**
22 | * IE11 requires the following for NgClass support on SVG elements
23 | */
24 | // import 'classlist.js'; // Run `npm install --save classlist.js`.
25 |
26 | /**
27 | * Web Animations `@angular/platform-browser/animations`
28 | * Only required if AnimationBuilder is used within the application and using IE/Edge or Safari.
29 | * Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0).
30 | */
31 | // import 'web-animations-js'; // Run `npm install --save web-animations-js`.
32 |
33 | /**
34 | * By default, zone.js will patch all possible macroTask and DomEvents
35 | * user can disable parts of macroTask/DomEvents patch by setting following flags
36 | * because those flags need to be set before `zone.js` being loaded, and webpack
37 | * will put import in the top of bundle, so user need to create a separate file
38 | * in this directory (for example: zone-flags.ts), and put the following flags
39 | * into that file, and then add the following code before importing zone.js.
40 | * import './zone-flags';
41 | *
42 | * The flags allowed in zone-flags.ts are listed here.
43 | *
44 | * The following flags will work for all browsers.
45 | *
46 | * (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame
47 | * (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick
48 | * (window as any).__zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames
49 | *
50 | * in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js
51 | * with the following flag, it will bypass `zone.js` patch for IE/Edge
52 | *
53 | * (window as any).__Zone_enable_cross_context_check = true;
54 | *
55 | */
56 |
57 | /***************************************************************************************************
58 | * Zone JS is required by default for Angular itself.
59 | */
60 | import 'zone.js'; // Included with Angular CLI.
61 |
62 |
63 | /***************************************************************************************************
64 | * APPLICATION IMPORTS
65 | */
66 |
--------------------------------------------------------------------------------
/angular.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
3 | "cli": {
4 | "analytics": false
5 | },
6 | "version": 1,
7 | "newProjectRoot": "projects",
8 | "projects": {
9 | "angular-router-guards-example": {
10 | "projectType": "application",
11 | "schematics": {
12 | "@schematics/angular:component": {
13 | "style": "scss"
14 | },
15 | "@schematics/angular:application": {
16 | "strict": true
17 | }
18 | },
19 | "root": "",
20 | "sourceRoot": "src",
21 | "prefix": "app",
22 | "architect": {
23 | "build": {
24 | "builder": "@angular-devkit/build-angular:browser",
25 | "options": {
26 | "outputPath": "dist/angular-router-guards-example",
27 | "index": "src/index.html",
28 | "main": "src/main.ts",
29 | "polyfills": "src/polyfills.ts",
30 | "tsConfig": "tsconfig.app.json",
31 | "inlineStyleLanguage": "scss",
32 | "assets": [
33 | "src/favicon.ico",
34 | "src/assets"
35 | ],
36 | "styles": [
37 | "./node_modules/@angular/material/prebuilt-themes/indigo-pink.css",
38 | "src/styles.scss"
39 | ],
40 | "scripts": []
41 | },
42 | "configurations": {
43 | "production": {
44 | "budgets": [
45 | {
46 | "type": "initial",
47 | "maximumWarning": "500kb",
48 | "maximumError": "1mb"
49 | },
50 | {
51 | "type": "anyComponentStyle",
52 | "maximumWarning": "2kb",
53 | "maximumError": "4kb"
54 | }
55 | ],
56 | "fileReplacements": [
57 | {
58 | "replace": "src/environments/environment.ts",
59 | "with": "src/environments/environment.prod.ts"
60 | }
61 | ],
62 | "outputHashing": "all"
63 | },
64 | "development": {
65 | "buildOptimizer": false,
66 | "optimization": false,
67 | "vendorChunk": true,
68 | "extractLicenses": false,
69 | "sourceMap": true,
70 | "namedChunks": true
71 | }
72 | },
73 | "defaultConfiguration": "production"
74 | },
75 | "serve": {
76 | "builder": "@angular-devkit/build-angular:dev-server",
77 | "configurations": {
78 | "production": {
79 | "browserTarget": "angular-router-guards-example:build:production"
80 | },
81 | "development": {
82 | "browserTarget": "angular-router-guards-example:build:development"
83 | }
84 | },
85 | "defaultConfiguration": "development"
86 | },
87 | "extract-i18n": {
88 | "builder": "@angular-devkit/build-angular:extract-i18n",
89 | "options": {
90 | "browserTarget": "angular-router-guards-example:build"
91 | }
92 | },
93 | "test": {
94 | "builder": "@angular-devkit/build-angular:karma",
95 | "options": {
96 | "main": "src/test.ts",
97 | "polyfills": "src/polyfills.ts",
98 | "tsConfig": "tsconfig.spec.json",
99 | "karmaConfig": "karma.conf.js",
100 | "inlineStyleLanguage": "scss",
101 | "assets": [
102 | "src/favicon.ico",
103 | "src/assets"
104 | ],
105 | "styles": [
106 | "./node_modules/@angular/material/prebuilt-themes/indigo-pink.css",
107 | "src/styles.scss"
108 | ],
109 | "scripts": []
110 | }
111 | }
112 | }
113 | }
114 | },
115 | "defaultProject": "angular-router-guards-example"
116 | }
117 |
--------------------------------------------------------------------------------
/src/app/admin/list/list-datasource.ts:
--------------------------------------------------------------------------------
1 | import { DataSource } from '@angular/cdk/collections';
2 | import { MatPaginator } from '@angular/material/paginator';
3 | import { MatSort } from '@angular/material/sort';
4 | import { map } from 'rxjs/operators';
5 | import { Observable, of as observableOf, merge } from 'rxjs';
6 |
7 | // TODO: Replace this with your own data model type
8 | export interface ListItem {
9 | name: string;
10 | id: number;
11 | }
12 |
13 | // TODO: replace this with real data from your application
14 | const EXAMPLE_DATA: ListItem[] = [
15 | {id: 1, name: 'Hydrogen'},
16 | {id: 2, name: 'Helium'},
17 | {id: 3, name: 'Lithium'},
18 | {id: 4, name: 'Beryllium'},
19 | {id: 5, name: 'Boron'},
20 | {id: 6, name: 'Carbon'},
21 | {id: 7, name: 'Nitrogen'},
22 | {id: 8, name: 'Oxygen'},
23 | {id: 9, name: 'Fluorine'},
24 | {id: 10, name: 'Neon'},
25 | {id: 11, name: 'Sodium'},
26 | {id: 12, name: 'Magnesium'},
27 | {id: 13, name: 'Aluminum'},
28 | {id: 14, name: 'Silicon'},
29 | {id: 15, name: 'Phosphorus'},
30 | {id: 16, name: 'Sulfur'},
31 | {id: 17, name: 'Chlorine'},
32 | {id: 18, name: 'Argon'},
33 | {id: 19, name: 'Potassium'},
34 | {id: 20, name: 'Calcium'},
35 | ];
36 |
37 | /**
38 | * Data source for the List view. This class should
39 | * encapsulate all logic for fetching and manipulating the displayed data
40 | * (including sorting, pagination, and filtering).
41 | */
42 | export class ListDataSource extends DataSource {
43 | data: ListItem[] = EXAMPLE_DATA;
44 | paginator: MatPaginator | undefined;
45 | sort: MatSort | undefined;
46 |
47 | constructor() {
48 | super();
49 | }
50 |
51 | /**
52 | * Connect this data source to the table. The table will only update when
53 | * the returned stream emits new items.
54 | * @returns A stream of the items to be rendered.
55 | */
56 | connect(): Observable {
57 | if (this.paginator && this.sort) {
58 | // Combine everything that affects the rendered data into one update
59 | // stream for the data-table to consume.
60 | return merge(observableOf(this.data), this.paginator.page, this.sort.sortChange)
61 | .pipe(map(() => {
62 | return this.getPagedData(this.getSortedData([...this.data ]));
63 | }));
64 | } else {
65 | throw Error('Please set the paginator and sort on the data source before connecting.');
66 | }
67 | }
68 |
69 | /**
70 | * Called when the table is being destroyed. Use this function, to clean up
71 | * any open connections or free any held resources that were set up during connect.
72 | */
73 | disconnect(): void {}
74 |
75 | /**
76 | * Paginate the data (client-side). If you're using server-side pagination,
77 | * this would be replaced by requesting the appropriate data from the server.
78 | */
79 | private getPagedData(data: ListItem[]): ListItem[] {
80 | if (this.paginator) {
81 | const startIndex = this.paginator.pageIndex * this.paginator.pageSize;
82 | return data.splice(startIndex, this.paginator.pageSize);
83 | } else {
84 | return data;
85 | }
86 | }
87 |
88 | /**
89 | * Sort the data (client-side). If you're using server-side sorting,
90 | * this would be replaced by requesting the appropriate data from the server.
91 | */
92 | private getSortedData(data: ListItem[]): ListItem[] {
93 | if (!this.sort || !this.sort.active || this.sort.direction === '') {
94 | return data;
95 | }
96 |
97 | return data.sort((a, b) => {
98 | const isAsc = this.sort?.direction === 'asc';
99 | switch (this.sort?.active) {
100 | case 'name': return compare(a.name, b.name, isAsc);
101 | case 'id': return compare(+a.id, +b.id, isAsc);
102 | default: return 0;
103 | }
104 | });
105 | }
106 | }
107 |
108 | /** Simple sort comparator for example ID/Name columns (for client-side sorting). */
109 | function compare(a: string | number, b: string | number, isAsc: boolean): number {
110 | return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
111 | }
112 |
--------------------------------------------------------------------------------