├── .browserslistrc ├── .editorconfig ├── .gitignore ├── .prettierrc ├── README.md ├── angular.json ├── e2e ├── protractor.conf.js ├── src │ ├── app.e2e-spec.ts │ └── app.po.ts └── tsconfig.json ├── karma.conf.js ├── package-lock.json ├── package.json ├── src ├── _redirects ├── app │ ├── abstract-change-detection.component.ts │ ├── app.component.html │ ├── app.component.scss │ ├── app.component.spec.ts │ ├── app.component.ts │ ├── app.module.ts │ ├── app.routes.ts │ ├── async-pipe-demo │ │ ├── async-pipe-demo.component.html │ │ ├── async-pipe-demo.component.scss │ │ ├── async-pipe-demo.component.spec.ts │ │ └── async-pipe-demo.component.ts │ ├── complex-demo │ │ ├── complex-demo.component.html │ │ ├── complex-demo.component.scss │ │ ├── complex-demo.component.spec.ts │ │ └── complex-demo.component.ts │ ├── components │ │ ├── hero-card-async-pipe │ │ │ ├── hero-card-async-pipe.component.html │ │ │ ├── hero-card-async-pipe.component.scss │ │ │ ├── hero-card-async-pipe.component.spec.ts │ │ │ └── hero-card-async-pipe.component.ts │ │ ├── hero-card-on-push │ │ │ ├── hero-card-on-push.component.scss │ │ │ ├── hero-card-on-push.component.spec.ts │ │ │ └── hero-card-on-push.component.ts │ │ ├── hero-card-template.ts │ │ ├── hero-card │ │ │ ├── hero-card.component.scss │ │ │ ├── hero-card.component.spec.ts │ │ │ └── hero-card.component.ts │ │ ├── hero-details │ │ │ ├── hero-details.component.html │ │ │ ├── hero-details.component.scss │ │ │ ├── hero-details.component.spec.ts │ │ │ └── hero-details.component.ts │ │ └── run-outside-angular-trigger │ │ │ ├── run-outside-angular-trigger.component.html │ │ │ ├── run-outside-angular-trigger.component.scss │ │ │ ├── run-outside-angular-trigger.component.spec.ts │ │ │ └── run-outside-angular-trigger.component.ts │ ├── detach-demo │ │ ├── detach-demo.component.html │ │ ├── detach-demo.component.scss │ │ ├── detach-demo.component.spec.ts │ │ └── detach-demo.component.ts │ ├── expression-changed-after-it-has-been-checked-error-demo │ │ ├── expression-changed-after-it-has-been-checked-error-demo.component.html │ │ ├── expression-changed-after-it-has-been-checked-error-demo.component.scss │ │ ├── expression-changed-after-it-has-been-checked-error-demo.component.spec.ts │ │ └── expression-changed-after-it-has-been-checked-error-demo.component.ts │ ├── home │ │ ├── home.component.html │ │ ├── home.component.scss │ │ ├── home.component.spec.ts │ │ └── home.component.ts │ ├── models │ │ └── hero.ts │ ├── simple-demo │ │ ├── simple-demo.component.html │ │ ├── simple-demo.component.scss │ │ ├── simple-demo.component.spec.ts │ │ └── simple-demo.component.ts │ └── utils │ │ └── utils.ts ├── assets │ ├── .gitkeep │ └── test-data │ │ └── test-hero.json ├── environments │ ├── environment.prod.ts │ └── environment.ts ├── favicon.ico ├── index.html ├── main.ts ├── polyfills.ts ├── styles.scss └── test.ts ├── tsconfig.app.json ├── tsconfig.json ├── tsconfig.spec.json └── tslint.json /.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 | # You can see what browsers were selected by your queries by running: 6 | # npx browserslist 7 | 8 | > 0.5% 9 | last 2 versions 10 | Firefox ESR 11 | not dead 12 | not IE 9-11 # For IE 9-11 support, remove 'not'. -------------------------------------------------------------------------------- /.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 | [*.md] 12 | max_line_length = off 13 | trim_trailing_whitespace = false 14 | -------------------------------------------------------------------------------- /.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 | speed-measure-plugin*.json 16 | 17 | # IDEs and editors 18 | /.idea 19 | .project 20 | .classpath 21 | .c9/ 22 | *.launch 23 | .settings/ 24 | *.sublime-workspace 25 | 26 | # IDE - VSCode 27 | .vscode/* 28 | !.vscode/settings.json 29 | !.vscode/tasks.json 30 | !.vscode/launch.json 31 | !.vscode/extensions.json 32 | .history/* 33 | 34 | # misc 35 | /.sass-cache 36 | /connect.lock 37 | /coverage 38 | /libpeerconnection.log 39 | npm-debug.log 40 | yarn-error.log 41 | testem.log 42 | /typings 43 | 44 | # System Files 45 | .DS_Store 46 | Thumbs.db 47 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true 3 | } 4 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Angular Change Detection Demo 2 | 3 | Deployed at [https://angular-change-detection-demo.netlify.com](https://angular-change-detection-demo.netlify.com) 4 | 5 | Corresponding blog post: [The Last Guide For Angular Change Detection You'll Ever Need](https://www.mokkapps.de/blog/the-last-guide-for-angular-change-detection-you-will-ever-need/) 6 | -------------------------------------------------------------------------------- /angular.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "./node_modules/@angular/cli/lib/config/schema.json", 3 | "version": 1, 4 | "newProjectRoot": "projects", 5 | "projects": { 6 | "change-detection-demo": { 7 | "projectType": "application", 8 | "schematics": { 9 | "@schematics/angular:component": { 10 | "style": "scss" 11 | } 12 | }, 13 | "root": "", 14 | "sourceRoot": "src", 15 | "prefix": "app", 16 | "architect": { 17 | "build": { 18 | "builder": "@angular-devkit/build-angular:browser", 19 | "options": { 20 | "outputPath": "dist/change-detection-demo", 21 | "index": "src/index.html", 22 | "main": "src/main.ts", 23 | "polyfills": "src/polyfills.ts", 24 | "tsConfig": "tsconfig.app.json", 25 | "aot": false, 26 | "assets": [ 27 | "src/favicon.ico", 28 | "src/assets", 29 | "src/_redirects" 30 | ], 31 | "styles": [ 32 | "./node_modules/@angular/material/prebuilt-themes/indigo-pink.css", 33 | "src/styles.scss" 34 | ], 35 | "scripts": [] 36 | }, 37 | "configurations": { 38 | "production": { 39 | "fileReplacements": [ 40 | { 41 | "replace": "src/environments/environment.ts", 42 | "with": "src/environments/environment.prod.ts" 43 | } 44 | ], 45 | "optimization": true, 46 | "outputHashing": "all", 47 | "sourceMap": false, 48 | "extractCss": true, 49 | "namedChunks": false, 50 | "aot": false, 51 | "extractLicenses": true, 52 | "vendorChunk": false, 53 | "buildOptimizer": false, 54 | "budgets": [ 55 | { 56 | "type": "initial", 57 | "maximumWarning": "2mb", 58 | "maximumError": "5mb" 59 | }, 60 | { 61 | "type": "anyComponentStyle", 62 | "maximumWarning": "6kb", 63 | "maximumError": "10kb" 64 | } 65 | ] 66 | } 67 | } 68 | }, 69 | "serve": { 70 | "builder": "@angular-devkit/build-angular:dev-server", 71 | "options": { 72 | "browserTarget": "change-detection-demo:build" 73 | }, 74 | "configurations": { 75 | "production": { 76 | "browserTarget": "change-detection-demo:build:production" 77 | } 78 | } 79 | }, 80 | "extract-i18n": { 81 | "builder": "@angular-devkit/build-angular:extract-i18n", 82 | "options": { 83 | "browserTarget": "change-detection-demo:build" 84 | } 85 | }, 86 | "test": { 87 | "builder": "@angular-devkit/build-angular:karma", 88 | "options": { 89 | "main": "src/test.ts", 90 | "polyfills": "src/polyfills.ts", 91 | "tsConfig": "tsconfig.spec.json", 92 | "karmaConfig": "karma.conf.js", 93 | "assets": [ 94 | "src/favicon.ico", 95 | "src/assets" 96 | ], 97 | "styles": [ 98 | "./node_modules/@angular/material/prebuilt-themes/indigo-pink.css", 99 | "src/styles.scss" 100 | ], 101 | "scripts": [] 102 | } 103 | }, 104 | "lint": { 105 | "builder": "@angular-devkit/build-angular:tslint", 106 | "options": { 107 | "tsConfig": [ 108 | "tsconfig.app.json", 109 | "tsconfig.spec.json", 110 | "e2e/tsconfig.json" 111 | ], 112 | "exclude": [ 113 | "**/node_modules/**" 114 | ] 115 | } 116 | }, 117 | "e2e": { 118 | "builder": "@angular-devkit/build-angular:protractor", 119 | "options": { 120 | "protractorConfig": "e2e/protractor.conf.js", 121 | "devServerTarget": "change-detection-demo:serve" 122 | }, 123 | "configurations": { 124 | "production": { 125 | "devServerTarget": "change-detection-demo:serve:production" 126 | } 127 | } 128 | } 129 | } 130 | } 131 | }, 132 | "defaultProject": "change-detection-demo" 133 | } 134 | -------------------------------------------------------------------------------- /e2e/protractor.conf.js: -------------------------------------------------------------------------------- 1 | // @ts-check 2 | // Protractor configuration file, see link for more information 3 | // https://github.com/angular/protractor/blob/master/lib/config.ts 4 | 5 | const { SpecReporter } = require('jasmine-spec-reporter'); 6 | 7 | /** 8 | * @type { import("protractor").Config } 9 | */ 10 | exports.config = { 11 | allScriptsTimeout: 11000, 12 | specs: [ 13 | './src/**/*.e2e-spec.ts' 14 | ], 15 | capabilities: { 16 | browserName: 'chrome' 17 | }, 18 | directConnect: true, 19 | baseUrl: 'http://localhost:4200/', 20 | framework: 'jasmine', 21 | jasmineNodeOpts: { 22 | showColors: true, 23 | defaultTimeoutInterval: 30000, 24 | print: function() {} 25 | }, 26 | onPrepare() { 27 | require('ts-node').register({ 28 | project: require('path').join(__dirname, './tsconfig.json') 29 | }); 30 | jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } })); 31 | } 32 | }; -------------------------------------------------------------------------------- /e2e/src/app.e2e-spec.ts: -------------------------------------------------------------------------------- 1 | import { AppPage } from './app.po'; 2 | import { browser, logging } from 'protractor'; 3 | 4 | describe('workspace-project App', () => { 5 | let page: AppPage; 6 | 7 | beforeEach(() => { 8 | page = new AppPage(); 9 | }); 10 | 11 | it('should display welcome message', () => { 12 | page.navigateTo(); 13 | expect(page.getTitleText()).toEqual('change-detection-demo app is running!'); 14 | }); 15 | 16 | afterEach(async () => { 17 | // Assert that there are no errors emitted from the browser 18 | const logs = await browser.manage().logs().get(logging.Type.BROWSER); 19 | expect(logs).not.toContain(jasmine.objectContaining({ 20 | level: logging.Level.SEVERE, 21 | } as logging.Entry)); 22 | }); 23 | }); 24 | -------------------------------------------------------------------------------- /e2e/src/app.po.ts: -------------------------------------------------------------------------------- 1 | import { browser, by, element } from 'protractor'; 2 | 3 | export class AppPage { 4 | navigateTo() { 5 | return browser.get(browser.baseUrl) as Promise; 6 | } 7 | 8 | getTitleText() { 9 | return element(by.css('app-root .content span')).getText() as Promise; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /e2e/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/e2e", 5 | "module": "commonjs", 6 | "target": "es2018", 7 | "types": [ 8 | "jasmine", 9 | "jasminewd2", 10 | "node" 11 | ] 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /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-istanbul-reporter'), 13 | require('@angular-devkit/build-angular/plugins/karma') 14 | ], 15 | client: { 16 | clearContext: false // leave Jasmine Spec Runner output visible in browser 17 | }, 18 | coverageIstanbulReporter: { 19 | dir: require('path').join(__dirname, './coverage/change-detection-demo'), 20 | reports: ['html', 'lcovonly', 'text-summary'], 21 | fixWebpackSourcePaths: true 22 | }, 23 | reporters: ['progress', 'kjhtml'], 24 | port: 9876, 25 | colors: true, 26 | logLevel: config.LOG_INFO, 27 | autoWatch: true, 28 | browsers: ['Chrome'], 29 | singleRun: false, 30 | restartOnFileChange: true 31 | }); 32 | }; 33 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "change-detection-demo", 3 | "version": "0.0.0", 4 | "scripts": { 5 | "ng": "ng", 6 | "start": "ng serve", 7 | "build": "ng build", 8 | "build:prod": "ng build --prod", 9 | "test": "ng test", 10 | "lint": "ng lint", 11 | "e2e": "ng e2e" 12 | }, 13 | "private": true, 14 | "dependencies": { 15 | "@angular/animations": "~10.1.3", 16 | "@angular/cdk": "~10.2.2", 17 | "@angular/common": "~10.1.3", 18 | "@angular/compiler": "~10.1.3", 19 | "@angular/core": "~10.1.3", 20 | "@angular/forms": "~10.1.3", 21 | "@angular/material": "^10.2.2", 22 | "@angular/platform-browser": "~10.1.3", 23 | "@angular/platform-browser-dynamic": "~10.1.3", 24 | "@angular/router": "~10.1.3", 25 | "faker": "^4.1.0", 26 | "rxjs": "~6.6.3", 27 | "tslib": "^2.0.0", 28 | "zone.js": "~0.10.2" 29 | }, 30 | "devDependencies": { 31 | "@angular-devkit/build-angular": "~0.1001.3", 32 | "@angular/cli": "~10.1.3", 33 | "@angular/compiler-cli": "~10.1.3", 34 | "@angular/language-service": "~10.1.3", 35 | "@types/jasmine": "~3.3.8", 36 | "@types/jasminewd2": "~2.0.3", 37 | "@types/node": "^12.11.1", 38 | "codelyzer": "^5.1.2", 39 | "jasmine-core": "~3.5.0", 40 | "jasmine-spec-reporter": "~5.0.0", 41 | "karma": "~5.0.0", 42 | "karma-chrome-launcher": "~3.1.0", 43 | "karma-coverage-istanbul-reporter": "~3.0.2", 44 | "karma-jasmine": "~4.0.0", 45 | "karma-jasmine-html-reporter": "^1.5.0", 46 | "prettier": "^2.1.2", 47 | "protractor": "~7.0.0", 48 | "ts-node": "~7.0.0", 49 | "tslint": "~6.1.0", 50 | "typescript": "~4.0.3" 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/_redirects: -------------------------------------------------------------------------------- 1 | # Rewrite all requests to any file that doesn’t already exist to the index page, where router can handle it. 2 | /* /index.html 200 3 | -------------------------------------------------------------------------------- /src/app/abstract-change-detection.component.ts: -------------------------------------------------------------------------------- 1 | import { ChangeDetectorRef, ElementRef, NgZone } from '@angular/core'; 2 | import { getNewHeroAge, getNewHeroName } from './utils/utils'; 3 | import { Hero } from './models/hero'; 4 | import { HttpClient } from '@angular/common/http'; 5 | 6 | export abstract class AbstractChangeDetectionComponent { 7 | hero: Hero; 8 | 9 | protected constructor( 10 | private el: ElementRef, 11 | private zone: NgZone, 12 | public cd: ChangeDetectorRef, 13 | private http: HttpClient 14 | ) {} 15 | 16 | changeName(): void { 17 | this.hero.name = getNewHeroName(); 18 | } 19 | 20 | changeAge(): void { 21 | this.hero.details.age = getNewHeroAge(); 22 | } 23 | 24 | loadNameViaHttp() { 25 | this.http 26 | .get<{ name: string }>(`./assets/test-data/test-hero.json`) 27 | .subscribe(res => { 28 | this.hero.name = `${res.name}`; 29 | }); 30 | } 31 | 32 | blink() { 33 | this.el.nativeElement.classList.add('highlight'); 34 | this.zone.runOutsideAngular(() => { 35 | setTimeout(() => { 36 | this.el.nativeElement.classList.remove('highlight'); 37 | }, 1500); 38 | }); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/app/app.component.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 7 | 8 | Change Detection Demos 9 | 10 | 11 | 12 | 18 | 21 | 22 | GitHub 27 | 28 | 29 | 30 | 31 | 32 | Home 33 | Simple Demo 34 | Detach Demo 35 | AsyncPipe Demo 36 | Expression Changed Demo 39 | Complex Demo 40 | 41 | 42 | 45 | 46 | 47 | Built with ♥ by Mokkapps | 49 | Source Code 53 | 54 | -------------------------------------------------------------------------------- /src/app/app.component.scss: -------------------------------------------------------------------------------- 1 | .sidenav-container { 2 | position: absolute; 3 | top: 60px; 4 | bottom: 60px; 5 | left: 0; 6 | right: 0; 7 | } 8 | 9 | .sidenav { 10 | display: flex; 11 | align-items: center; 12 | justify-content: center; 13 | width: 200px; 14 | background: lightgray; 15 | border-right: 1px solid black; 16 | } 17 | 18 | .fill-remaining-space { 19 | flex: 1 1 auto; 20 | } 21 | 22 | .link { 23 | color: white; 24 | } 25 | 26 | .header { 27 | position: fixed; 28 | top: 0; 29 | left: 0; 30 | right: 0; 31 | } 32 | 33 | .footer { 34 | position: fixed; 35 | bottom: 0; 36 | left: 0; 37 | right: 0; 38 | } 39 | -------------------------------------------------------------------------------- /src/app/app.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { TestBed, async } from '@angular/core/testing'; 2 | import { AppComponent } from './app.component'; 3 | 4 | describe('AppComponent', () => { 5 | beforeEach(async(() => { 6 | TestBed.configureTestingModule({ 7 | declarations: [ 8 | AppComponent 9 | ], 10 | }).compileComponents(); 11 | })); 12 | 13 | it('should create the app', () => { 14 | const fixture = TestBed.createComponent(AppComponent); 15 | const app = fixture.debugElement.componentInstance; 16 | expect(app).toBeTruthy(); 17 | }); 18 | 19 | it(`should have as title 'change-detection-demo'`, () => { 20 | const fixture = TestBed.createComponent(AppComponent); 21 | const app = fixture.debugElement.componentInstance; 22 | expect(app.title).toEqual('change-detection-demo'); 23 | }); 24 | 25 | it('should render title', () => { 26 | const fixture = TestBed.createComponent(AppComponent); 27 | fixture.detectChanges(); 28 | const compiled = fixture.debugElement.nativeElement; 29 | expect(compiled.querySelector('.content span').textContent).toContain('change-detection-demo app is running!'); 30 | }); 31 | }); 32 | -------------------------------------------------------------------------------- /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 | constructor() {} 10 | } 11 | -------------------------------------------------------------------------------- /src/app/app.module.ts: -------------------------------------------------------------------------------- 1 | import { BrowserModule } from '@angular/platform-browser'; 2 | import { NgModule } from '@angular/core'; 3 | 4 | import { AppComponent } from './app.component'; 5 | import { FormsModule } from '@angular/forms'; 6 | import { RouterModule } from '@angular/router'; 7 | import { NoopAnimationsModule } from '@angular/platform-browser/animations'; 8 | import { MatButtonModule } from '@angular/material/button'; 9 | import { MatCardModule } from '@angular/material/card'; 10 | import { MatDividerModule } from '@angular/material/divider'; 11 | import { MatExpansionModule } from '@angular/material/expansion'; 12 | import { MatFormFieldModule } from '@angular/material/form-field'; 13 | import { MatInputModule } from '@angular/material/input'; 14 | import { MatListModule } from '@angular/material/list'; 15 | import { MatSidenavModule } from '@angular/material/sidenav'; 16 | import { MatToolbarModule } from '@angular/material/toolbar'; 17 | import { MatTooltipModule } from '@angular/material/tooltip'; 18 | import { SimpleDemoComponent } from './simple-demo/simple-demo.component'; 19 | import { HomeComponent } from './home/home.component'; 20 | import { HeroCardComponent } from './components/hero-card/hero-card.component'; 21 | import { HeroDetailsComponent } from './components/hero-details/hero-details.component'; 22 | import { HttpClientModule } from '@angular/common/http'; 23 | import { HeroCardOnPushComponent } from './components/hero-card-on-push/hero-card-on-push.component'; 24 | import { ComplexDemoComponent } from './complex-demo/complex-demo.component'; 25 | import { DetachDemoComponent } from './detach-demo/detach-demo.component'; 26 | import { APP_ROUTES } from './app.routes'; 27 | import { ExpressionChangedAfterItHasBeenCheckedErrorDemoComponent } from './expression-changed-after-it-has-been-checked-error-demo/expression-changed-after-it-has-been-checked-error-demo.component'; 28 | import { AsyncPipeDemoComponent } from './async-pipe-demo/async-pipe-demo.component'; 29 | import { HeroCardAsyncPipeComponent } from './components/hero-card-async-pipe/hero-card-async-pipe.component'; 30 | import { RunOutsideAngularTriggerComponent } from './components/run-outside-angular-trigger/run-outside-angular-trigger.component'; 31 | 32 | @NgModule({ 33 | declarations: [ 34 | AppComponent, 35 | SimpleDemoComponent, 36 | HomeComponent, 37 | HeroCardComponent, 38 | HeroDetailsComponent, 39 | HeroCardOnPushComponent, 40 | ComplexDemoComponent, 41 | DetachDemoComponent, 42 | ExpressionChangedAfterItHasBeenCheckedErrorDemoComponent, 43 | AsyncPipeDemoComponent, 44 | HeroCardAsyncPipeComponent, 45 | RunOutsideAngularTriggerComponent 46 | ], 47 | imports: [ 48 | BrowserModule, 49 | FormsModule, 50 | HttpClientModule, 51 | RouterModule.forRoot(APP_ROUTES), 52 | NoopAnimationsModule, 53 | MatToolbarModule, 54 | MatButtonModule, 55 | MatCardModule, 56 | MatDividerModule, 57 | MatExpansionModule, 58 | MatFormFieldModule, 59 | MatInputModule, 60 | MatTooltipModule, 61 | MatSidenavModule, 62 | MatListModule 63 | ], 64 | providers: [], 65 | bootstrap: [AppComponent] 66 | }) 67 | export class AppModule {} 68 | -------------------------------------------------------------------------------- /src/app/app.routes.ts: -------------------------------------------------------------------------------- 1 | import { Routes } from '@angular/router'; 2 | import { HomeComponent } from './home/home.component'; 3 | import { SimpleDemoComponent } from './simple-demo/simple-demo.component'; 4 | import { ComplexDemoComponent } from './complex-demo/complex-demo.component'; 5 | import { DetachDemoComponent } from './detach-demo/detach-demo.component'; 6 | import { ExpressionChangedAfterItHasBeenCheckedErrorDemoComponent } from './expression-changed-after-it-has-been-checked-error-demo/expression-changed-after-it-has-been-checked-error-demo.component'; 7 | import {AsyncPipeDemoComponent} from './async-pipe-demo/async-pipe-demo.component'; 8 | 9 | export const APP_ROUTES: Routes = [ 10 | { 11 | path: '', 12 | redirectTo: '/home', 13 | pathMatch: 'full' 14 | }, 15 | { 16 | path: 'home', 17 | component: HomeComponent 18 | }, 19 | { 20 | path: 'simple-demo', 21 | component: SimpleDemoComponent 22 | }, 23 | { 24 | path: 'complex-demo', 25 | component: ComplexDemoComponent 26 | }, 27 | { 28 | path: 'detach-demo', 29 | component: DetachDemoComponent 30 | }, 31 | { 32 | path: 'async-pipe-demo', 33 | component: AsyncPipeDemoComponent 34 | }, 35 | { 36 | path: 'expression-changed-demo', 37 | component: ExpressionChangedAfterItHasBeenCheckedErrorDemoComponent 38 | }, 39 | { 40 | path: '**', 41 | redirectTo: 'home' 42 | } 43 | ]; 44 | -------------------------------------------------------------------------------- /src/app/async-pipe-demo/async-pipe-demo.component.html: -------------------------------------------------------------------------------- 1 |

AsyncPipe & OnPush

2 | 3 |

OnPush With Async Pipe

4 | 5 | 6 | 7 | Each emitted value marks the component for CD 8 | 9 | 10 |
11 | 12 |
13 |

OnPush Without Async Pipe

14 | 15 | 16 | 17 | Observable interval inside the component does not trigger CD 18 | 19 | 20 |
21 | 22 |
23 | -------------------------------------------------------------------------------- /src/app/async-pipe-demo/async-pipe-demo.component.scss: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mokkapps/angular-change-detection-demo/f096e99c6d8e03ed49bbfd3925985c209662ffc1/src/app/async-pipe-demo/async-pipe-demo.component.scss -------------------------------------------------------------------------------- /src/app/async-pipe-demo/async-pipe-demo.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { AsyncPipeDemoComponent } from './async-pipe-demo.component'; 4 | 5 | describe('AsyncPipeDemoComponent', () => { 6 | let component: AsyncPipeDemoComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(async(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ AsyncPipeDemoComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(AsyncPipeDemoComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /src/app/async-pipe-demo/async-pipe-demo.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | 3 | @Component({ 4 | selector: 'app-async-pipe-demo', 5 | templateUrl: './async-pipe-demo.component.html', 6 | styleUrls: ['./async-pipe-demo.component.scss'] 7 | }) 8 | export class AsyncPipeDemoComponent { 9 | constructor() {} 10 | } 11 | -------------------------------------------------------------------------------- /src/app/complex-demo/complex-demo.component.html: -------------------------------------------------------------------------------- 1 |

Edu Change Detection

2 |

Checkout this nice complex demo which I inserted via iframe. Source: GitHub

3 | 4 | -------------------------------------------------------------------------------- /src/app/complex-demo/complex-demo.component.scss: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mokkapps/angular-change-detection-demo/f096e99c6d8e03ed49bbfd3925985c209662ffc1/src/app/complex-demo/complex-demo.component.scss -------------------------------------------------------------------------------- /src/app/complex-demo/complex-demo.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { ComplexDemoComponent } from './complex-demo.component'; 4 | 5 | describe('ComplexDemoComponent', () => { 6 | let component: ComplexDemoComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(async(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ ComplexDemoComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(ComplexDemoComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /src/app/complex-demo/complex-demo.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | 3 | @Component({ 4 | selector: 'app-complex-demo', 5 | templateUrl: './complex-demo.component.html', 6 | styleUrls: ['./complex-demo.component.scss'] 7 | }) 8 | export class ComplexDemoComponent { 9 | constructor() {} 10 | } 11 | -------------------------------------------------------------------------------- /src/app/components/hero-card-async-pipe/hero-card-async-pipe.component.html: -------------------------------------------------------------------------------- 1 | {{ blink() }} 2 | 3 | 4 | 5 | HeroCardAsyncPipeOnPush 6 | {{ 7 | (hero$ | async).name 8 | }} 9 | {{ 10 | (hero$ | async).id 11 | }} 12 | {{ hero.name }} 13 | {{ hero.id }} 14 | 15 | 16 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /src/app/components/hero-card-async-pipe/hero-card-async-pipe.component.scss: -------------------------------------------------------------------------------- 1 | :host(.highlight) { 2 | border: 2px solid orangered; 3 | } 4 | -------------------------------------------------------------------------------- /src/app/components/hero-card-async-pipe/hero-card-async-pipe.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { HeroCardAsyncPipeComponent } from './hero-card-async-pipe.component'; 4 | 5 | describe('HeroCardAsyncPipeComponent', () => { 6 | let component: HeroCardAsyncPipeComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(async(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ HeroCardAsyncPipeComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(HeroCardAsyncPipeComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /src/app/components/hero-card-async-pipe/hero-card-async-pipe.component.ts: -------------------------------------------------------------------------------- 1 | import { 2 | ChangeDetectionStrategy, 3 | ChangeDetectorRef, 4 | Component, 5 | ElementRef, 6 | Input, 7 | NgZone, 8 | OnDestroy, 9 | OnInit 10 | } from '@angular/core'; 11 | import { HttpClient } from '@angular/common/http'; 12 | import { AbstractChangeDetectionComponent } from '../../abstract-change-detection.component'; 13 | import { interval, Observable, Subscription } from 'rxjs'; 14 | import { Hero } from '../../models/hero'; 15 | import { map, startWith } from 'rxjs/operators'; 16 | import { createHero } from '../../utils/utils'; 17 | 18 | @Component({ 19 | selector: 'app-hero-card-async-pipe', 20 | templateUrl: './hero-card-async-pipe.component.html', 21 | styleUrls: ['./hero-card-async-pipe.component.scss'], 22 | changeDetection: ChangeDetectionStrategy.OnPush 23 | }) 24 | export class HeroCardAsyncPipeComponent extends AbstractChangeDetectionComponent 25 | implements OnInit, OnDestroy { 26 | @Input() useAsyncPipe: boolean; 27 | hero$: Observable; 28 | hero: Hero = createHero(); 29 | private subscription?: Subscription; 30 | 31 | constructor( 32 | el: ElementRef, 33 | zone: NgZone, 34 | cd: ChangeDetectorRef, 35 | http: HttpClient 36 | ) { 37 | super(el, zone, cd, http); 38 | } 39 | 40 | ngOnInit(): void { 41 | if (this.useAsyncPipe) { 42 | this.hero$ = interval(1000).pipe( 43 | startWith(createHero()), 44 | map(() => createHero()) 45 | ); 46 | } else { 47 | this.subscription = interval(1000) 48 | .pipe(map(() => createHero())) 49 | .subscribe(() => { 50 | this.hero = createHero(); 51 | console.log( 52 | 'HeroCardAsyncPipeComponent new hero without AsyncPipe: ', 53 | this.hero 54 | ); 55 | }); 56 | } 57 | } 58 | 59 | ngOnDestroy() { 60 | if (this.subscription) { 61 | this.subscription.unsubscribe(); 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/app/components/hero-card-on-push/hero-card-on-push.component.scss: -------------------------------------------------------------------------------- 1 | :host(.highlight) { 2 | border: 2px solid orangered; 3 | } 4 | -------------------------------------------------------------------------------- /src/app/components/hero-card-on-push/hero-card-on-push.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { HeroCardOnPushComponent } from './hero-card-on-push.component'; 4 | 5 | describe('HeroCardOnPushComponent', () => { 6 | let component: HeroCardOnPushComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(async(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ HeroCardOnPushComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(HeroCardOnPushComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /src/app/components/hero-card-on-push/hero-card-on-push.component.ts: -------------------------------------------------------------------------------- 1 | import { 2 | ChangeDetectionStrategy, 3 | ChangeDetectorRef, 4 | Component, 5 | ElementRef, 6 | Input, 7 | NgZone 8 | } from '@angular/core'; 9 | import { AbstractChangeDetectionComponent } from '../../abstract-change-detection.component'; 10 | import { Hero } from '../../models/hero'; 11 | import { HttpClient } from '@angular/common/http'; 12 | import { getHeroCardTemplate } from '../hero-card-template'; 13 | 14 | @Component({ 15 | selector: 'app-hero-card-on-push', 16 | template: getHeroCardTemplate('HeroCardOnPushComponent'), 17 | styleUrls: ['./hero-card-on-push.component.scss'], 18 | changeDetection: ChangeDetectionStrategy.OnPush 19 | }) 20 | export class HeroCardOnPushComponent extends AbstractChangeDetectionComponent { 21 | @Input() hero: Hero; 22 | 23 | constructor( 24 | el: ElementRef, 25 | zone: NgZone, 26 | cd: ChangeDetectorRef, 27 | http: HttpClient 28 | ) { 29 | super(el, zone, cd, http); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/app/components/hero-card-template.ts: -------------------------------------------------------------------------------- 1 | export function getHeroCardTemplate( 2 | componentName: string = 'HeroCardComponent' 3 | ): string { 4 | return ` 5 | {{ blink() }} 6 | 7 | 8 | ${componentName} 9 | {{ hero.name }} 10 | {{ hero.id }} 11 | 12 | 13 | 14 | 15 | 16 |
17 | 20 | 23 | 26 |
27 |
28 | 31 | 34 | 37 | 40 |
41 |
42 |
43 | `; 44 | } 45 | -------------------------------------------------------------------------------- /src/app/components/hero-card/hero-card.component.scss: -------------------------------------------------------------------------------- 1 | :host(.highlight) { 2 | border: 2px solid orangered; 3 | } 4 | -------------------------------------------------------------------------------- /src/app/components/hero-card/hero-card.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { HeroCardComponent } from './card.component'; 4 | 5 | describe('CardComponent', () => { 6 | let component: HeroCardComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(async(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ HeroCardComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(HeroCardComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /src/app/components/hero-card/hero-card.component.ts: -------------------------------------------------------------------------------- 1 | import { 2 | ChangeDetectorRef, 3 | Component, 4 | ElementRef, 5 | Input, 6 | NgZone 7 | } from '@angular/core'; 8 | import { Hero } from '../../models/hero'; 9 | import { HttpClient } from '@angular/common/http'; 10 | import { AbstractChangeDetectionComponent } from '../../abstract-change-detection.component'; 11 | import { getHeroCardTemplate } from '../hero-card-template'; 12 | 13 | @Component({ 14 | selector: 'app-hero-card', 15 | template: getHeroCardTemplate(), 16 | styleUrls: ['./hero-card.component.scss'] 17 | }) 18 | export class HeroCardComponent extends AbstractChangeDetectionComponent { 19 | @Input() hero: Hero; 20 | 21 | constructor( 22 | el: ElementRef, 23 | zone: NgZone, 24 | cd: ChangeDetectorRef, 25 | http: HttpClient 26 | ) { 27 | super(el, zone, cd, http); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/app/components/hero-details/hero-details.component.html: -------------------------------------------------------------------------------- 1 | {{blink()}} 2 |
3 | HeroDetailsComponent 4 |
5 | 6 | 12 | 13 | 14 | 20 | 21 |
22 |
23 | -------------------------------------------------------------------------------- /src/app/components/hero-details/hero-details.component.scss: -------------------------------------------------------------------------------- 1 | .wrapper { 2 | border: 1px solid black; 3 | } 4 | 5 | :host(.highlight .wrapper) { 6 | border: 2px solid orangered; 7 | } 8 | -------------------------------------------------------------------------------- /src/app/components/hero-details/hero-details.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { HeroDetailsComponent } from './hero-details.component'; 4 | 5 | describe('HeroDetailsComponent', () => { 6 | let component: HeroDetailsComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [HeroDetailsComponent] 12 | }).compileComponents(); 13 | }); 14 | 15 | beforeEach(() => { 16 | fixture = TestBed.createComponent(HeroDetailsComponent); 17 | component = fixture.componentInstance; 18 | fixture.detectChanges(); 19 | }); 20 | 21 | it('should create', () => { 22 | expect(component).toBeTruthy(); 23 | }); 24 | }); 25 | -------------------------------------------------------------------------------- /src/app/components/hero-details/hero-details.component.ts: -------------------------------------------------------------------------------- 1 | import { 2 | ChangeDetectorRef, 3 | Component, 4 | ElementRef, 5 | Input, 6 | NgZone 7 | } from '@angular/core'; 8 | import { Hero } from '../../models/hero'; 9 | import { AbstractChangeDetectionComponent } from '../../abstract-change-detection.component'; 10 | import { HttpClient } from '@angular/common/http'; 11 | 12 | @Component({ 13 | selector: 'app-hero-details', 14 | templateUrl: './hero-details.component.html', 15 | styleUrls: ['./hero-details.component.scss'] 16 | }) 17 | export class HeroDetailsComponent extends AbstractChangeDetectionComponent { 18 | @Input() hero: Hero; 19 | 20 | constructor( 21 | el: ElementRef, 22 | zone: NgZone, 23 | cd: ChangeDetectorRef, 24 | http: HttpClient 25 | ) { 26 | super(el, zone, cd, http); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/app/components/run-outside-angular-trigger/run-outside-angular-trigger.component.html: -------------------------------------------------------------------------------- 1 | 4 | -------------------------------------------------------------------------------- /src/app/components/run-outside-angular-trigger/run-outside-angular-trigger.component.scss: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mokkapps/angular-change-detection-demo/f096e99c6d8e03ed49bbfd3925985c209662ffc1/src/app/components/run-outside-angular-trigger/run-outside-angular-trigger.component.scss -------------------------------------------------------------------------------- /src/app/components/run-outside-angular-trigger/run-outside-angular-trigger.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { RunOutsideAngularTriggerComponent } from './run-outside-angular-trigger.component'; 4 | 5 | describe('RunOutsideAngularTriggerComponent', () => { 6 | let component: RunOutsideAngularTriggerComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(async(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ RunOutsideAngularTriggerComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(RunOutsideAngularTriggerComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /src/app/components/run-outside-angular-trigger/run-outside-angular-trigger.component.ts: -------------------------------------------------------------------------------- 1 | import { 2 | AfterViewInit, 3 | ChangeDetectorRef, 4 | Component, 5 | ElementRef, 6 | NgZone, 7 | OnDestroy, 8 | ViewChild 9 | } from '@angular/core'; 10 | import { fromEvent, Subscription } from 'rxjs'; 11 | import { MatButton } from '@angular/material/button'; 12 | 13 | @Component({ 14 | selector: 'app-run-outside-angular-trigger', 15 | templateUrl: './run-outside-angular-trigger.component.html', 16 | styleUrls: ['./run-outside-angular-trigger.component.scss'] 17 | }) 18 | export class RunOutsideAngularTriggerComponent 19 | implements AfterViewInit, OnDestroy { 20 | @ViewChild('outsideZoneButton', { static: true }) myButton: MatButton; 21 | private subscription?: Subscription; 22 | 23 | constructor(private cd: ChangeDetectorRef, private ngZone: NgZone) { 24 | this.cd.detach(); 25 | } 26 | 27 | ngAfterViewInit() { 28 | this.ngZone.runOutsideAngular(() => { 29 | this.subscription = fromEvent( 30 | this.myButton._elementRef.nativeElement, 31 | 'click' 32 | ).subscribe(e => { 33 | console.log('setTimeout did not trigger change detection!'); 34 | }); 35 | }); 36 | } 37 | 38 | ngOnDestroy(): void { 39 | if (this.subscription) { 40 | this.subscription.unsubscribe(); 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/app/detach-demo/detach-demo.component.html: -------------------------------------------------------------------------------- 1 |

Deactivate And Manually Trigger Change Detection

2 | 3 | 4 |
    5 |
  • Click on "Detach" in card to deactivate change detection
  • 6 |
  • Clicking on "Detect Changes" updates the view manually
  • 7 |
8 |
9 |
10 |

{{ hero | json }}

11 |
12 | 13 |
14 | -------------------------------------------------------------------------------- /src/app/detach-demo/detach-demo.component.scss: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mokkapps/angular-change-detection-demo/f096e99c6d8e03ed49bbfd3925985c209662ffc1/src/app/detach-demo/detach-demo.component.scss -------------------------------------------------------------------------------- /src/app/detach-demo/detach-demo.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { DetachDemoComponent } from './detach-demo.component'; 4 | 5 | describe('DetachDemoComponent', () => { 6 | let component: DetachDemoComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(async(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ DetachDemoComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(DetachDemoComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /src/app/detach-demo/detach-demo.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnDestroy, OnInit } from '@angular/core'; 2 | import { interval, Subscription } from 'rxjs'; 3 | import { Hero } from '../models/hero'; 4 | import { createHero } from '../utils/utils'; 5 | import { map } from 'rxjs/operators'; 6 | 7 | @Component({ 8 | selector: 'app-detach-demo', 9 | templateUrl: './detach-demo.component.html', 10 | styleUrls: ['./detach-demo.component.scss'] 11 | }) 12 | export class DetachDemoComponent implements OnDestroy, OnInit { 13 | hero: Hero = createHero(); 14 | private subscription?: Subscription; 15 | 16 | constructor() {} 17 | 18 | ngOnInit(): void { 19 | this.subscription = interval(1000) 20 | .pipe(map(() => {})) 21 | .subscribe(v => { 22 | this.hero = createHero(); 23 | }); 24 | } 25 | 26 | ngOnDestroy(): void { 27 | if (this.subscription) { 28 | this.subscription.unsubscribe(); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/app/expression-changed-after-it-has-been-checked-error-demo/expression-changed-after-it-has-been-checked-error-demo.component.html: -------------------------------------------------------------------------------- 1 |

ExpressionChangedAfterItHasBeenCheckedError Demo

2 | 3 | 4 |
    5 |
  • Name is changed in ngAfterViewInit, open browser console to see the error
  • 6 |
  • View generation process (which ngAfterViewInit is a part of) is itself further modifying the data that we are trying to display in the first place
  • 7 |
8 |
9 |
10 |

{{ hero | json }}

11 |
12 | 13 |
14 | -------------------------------------------------------------------------------- /src/app/expression-changed-after-it-has-been-checked-error-demo/expression-changed-after-it-has-been-checked-error-demo.component.scss: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mokkapps/angular-change-detection-demo/f096e99c6d8e03ed49bbfd3925985c209662ffc1/src/app/expression-changed-after-it-has-been-checked-error-demo/expression-changed-after-it-has-been-checked-error-demo.component.scss -------------------------------------------------------------------------------- /src/app/expression-changed-after-it-has-been-checked-error-demo/expression-changed-after-it-has-been-checked-error-demo.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { ExpressionChangedAfterItHasBeenCheckedErrorDemoComponent } from './expression-changed-after-it-has-been-checked-error-demo.component'; 4 | 5 | describe('ExpressionChangedAfterItHasBeenCheckedErrorDemoComponent', () => { 6 | let component: ExpressionChangedAfterItHasBeenCheckedErrorDemoComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(async(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ ExpressionChangedAfterItHasBeenCheckedErrorDemoComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(ExpressionChangedAfterItHasBeenCheckedErrorDemoComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /src/app/expression-changed-after-it-has-been-checked-error-demo/expression-changed-after-it-has-been-checked-error-demo.component.ts: -------------------------------------------------------------------------------- 1 | import { AfterViewInit, Component } from '@angular/core'; 2 | import { Hero } from '../models/hero'; 3 | import { createHero } from '../utils/utils'; 4 | 5 | @Component({ 6 | selector: 'app-expression-changed-after-it-has-been-checked-error-demo', 7 | templateUrl: 8 | './expression-changed-after-it-has-been-checked-error-demo.component.html', 9 | styleUrls: [ 10 | './expression-changed-after-it-has-been-checked-error-demo.component.scss' 11 | ] 12 | }) 13 | export class ExpressionChangedAfterItHasBeenCheckedErrorDemoComponent 14 | implements AfterViewInit { 15 | hero: Hero = createHero(); 16 | 17 | constructor() {} 18 | 19 | ngAfterViewInit(): void { 20 | this.hero.name = 'Another name which triggers ExpressionChangedAfterItHasBeenCheckedError'; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/app/home/home.component.html: -------------------------------------------------------------------------------- 1 |

Welcome To Angular's Change Detection Demos

2 | 3 | 4 | 5 | 6 |

Used Angular version: {{angularVersion}}

7 | 8 | 9 | This page is not optimized for mobile phones! 10 | 11 | 12 | 13 |

Corresponding Blog Post

14 | Angular's Change Detection 15 | 16 |

Used Libraries

17 | Angular Material Design 18 | Faker.js to generate fake data 19 | -------------------------------------------------------------------------------- /src/app/home/home.component.scss: -------------------------------------------------------------------------------- 1 | :host { 2 | display: flex; 3 | flex-direction: column; 4 | align-content: center; 5 | align-items: center; 6 | } 7 | -------------------------------------------------------------------------------- /src/app/home/home.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { HomeComponent } from './home.component'; 4 | 5 | describe('HomeComponent', () => { 6 | let component: HomeComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(async(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ HomeComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(HomeComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /src/app/home/home.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit, VERSION } from '@angular/core'; 2 | 3 | @Component({ 4 | selector: 'app-home', 5 | templateUrl: './home.component.html', 6 | styleUrls: ['./home.component.scss'] 7 | }) 8 | export class HomeComponent implements OnInit { 9 | constructor() {} 10 | 11 | ngOnInit() {} 12 | 13 | get angularVersion(): string { 14 | return VERSION.full; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/app/models/hero.ts: -------------------------------------------------------------------------------- 1 | export interface Hero { 2 | id: string; 3 | name: string; 4 | details: HeroDetails; 5 | } 6 | 7 | export interface HeroDetails { 8 | age: number; 9 | country: string; 10 | } 11 | -------------------------------------------------------------------------------- /src/app/simple-demo/simple-demo.component.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | If a component is checked by ChangeDetector it is highlighted with a red border 4 | 5 | 6 | 7 |

Global Actions

8 |
9 | 12 | 13 | 16 | 19 | 22 |

{{ time | date: 'h:mm:ss' }}

23 |
24 | 25 | 26 | 27 | 28 | Modify Heroes 29 | 30 | 31 | 32 |
33 | 34 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 49 |
50 |
51 | 52 |

ChangeDetectionStrategy.Default

53 |
54 | 55 |
56 | 57 |

ChangeDetectionStrategy.OnPush

58 |
59 | 60 |
61 | -------------------------------------------------------------------------------- /src/app/simple-demo/simple-demo.component.scss: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mokkapps/angular-change-detection-demo/f096e99c6d8e03ed49bbfd3925985c209662ffc1/src/app/simple-demo/simple-demo.component.scss -------------------------------------------------------------------------------- /src/app/simple-demo/simple-demo.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { SimpleDemoComponent } from './simple-demo.component'; 4 | 5 | describe('SimpleDemoComponent', () => { 6 | let component: SimpleDemoComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(async(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ SimpleDemoComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(SimpleDemoComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /src/app/simple-demo/simple-demo.component.ts: -------------------------------------------------------------------------------- 1 | import { 2 | ApplicationRef, 3 | ChangeDetectorRef, 4 | Component, 5 | OnInit 6 | } from '@angular/core'; 7 | import { Hero } from '../models/hero'; 8 | import { createHero } from '../utils/utils'; 9 | import { interval, Subscription } from 'rxjs'; 10 | import { map } from 'rxjs/operators'; 11 | 12 | @Component({ 13 | selector: 'app-simple-demo', 14 | templateUrl: './simple-demo.component.html', 15 | styleUrls: ['./simple-demo.component.scss'] 16 | }) 17 | export class SimpleDemoComponent implements OnInit { 18 | heroes: Hero[] = []; 19 | time: Date; 20 | timeSubscription?: Subscription; 21 | 22 | constructor(private ref: ApplicationRef, private cd: ChangeDetectorRef) {} 23 | 24 | ngOnInit() { 25 | this.heroes.push(createHero()); 26 | } 27 | 28 | addHero(): void { 29 | this.heroes.push(createHero()); 30 | } 31 | 32 | createNewHero(id: string): void { 33 | const index = this.heroes.findIndex(h => h.id === id); 34 | const newHeroes = [...this.heroes]; 35 | newHeroes[index] = createHero(); 36 | this.heroes = newHeroes; 37 | } 38 | 39 | triggerSetTimeout() { 40 | setTimeout(() => {}); 41 | } 42 | 43 | triggerTick() { 44 | this.ref.tick(); 45 | } 46 | 47 | triggerMarkForCheck() { 48 | this.cd.markForCheck(); 49 | } 50 | 51 | triggerObservableTime(): void { 52 | if (this.timeSubscription) { 53 | this.timeSubscription.unsubscribe(); 54 | this.timeSubscription = undefined; 55 | return; 56 | } 57 | 58 | this.timeSubscription = interval(1000) 59 | .pipe(map(i => new Date())) 60 | .subscribe(time => { 61 | this.time = time; 62 | }); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/app/utils/utils.ts: -------------------------------------------------------------------------------- 1 | import { Hero } from '../models/hero'; 2 | import * as faker from 'faker'; 3 | 4 | export function createHero(): Hero { 5 | return { 6 | id: faker.random.uuid(), 7 | name: faker.name.findName(), 8 | details: { 9 | age: faker.random.number(), 10 | country: faker.address.country() 11 | } 12 | }; 13 | } 14 | 15 | export function getNewHeroName(): string { 16 | return faker.name.findName(); 17 | } 18 | 19 | export function getNewHeroAge(): number { 20 | return faker.random.number(); 21 | } 22 | -------------------------------------------------------------------------------- /src/assets/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mokkapps/angular-change-detection-demo/f096e99c6d8e03ed49bbfd3925985c209662ffc1/src/assets/.gitkeep -------------------------------------------------------------------------------- /src/assets/test-data/test-hero.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Captain America" 3 | } 4 | -------------------------------------------------------------------------------- /src/environments/environment.prod.ts: -------------------------------------------------------------------------------- 1 | export const environment = { 2 | production: true 3 | }; 4 | -------------------------------------------------------------------------------- /src/environments/environment.ts: -------------------------------------------------------------------------------- 1 | // This file can be replaced during build by using the `fileReplacements` array. 2 | // `ng build --prod` 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/dist/zone-error'; // Included with Angular CLI. 17 | -------------------------------------------------------------------------------- /src/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mokkapps/angular-change-detection-demo/f096e99c6d8e03ed49bbfd3925985c209662ffc1/src/favicon.ico -------------------------------------------------------------------------------- /src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Angular Change Detection Demos 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /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/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 | /** IE10 and IE11 requires the following for NgClass support on SVG elements */ 22 | // import 'classlist.js'; // Run `npm install --save classlist.js`. 23 | 24 | /** 25 | * Web Animations `@angular/platform-browser/animations` 26 | * Only required if AnimationBuilder is used within the application and using IE/Edge or Safari. 27 | * Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0). 28 | */ 29 | // import 'web-animations-js'; // Run `npm install --save web-animations-js`. 30 | 31 | /** 32 | * By default, zone.js will patch all possible macroTask and DomEvents 33 | * user can disable parts of macroTask/DomEvents patch by setting following flags 34 | * because those flags need to be set before `zone.js` being loaded, and webpack 35 | * will put import in the top of bundle, so user need to create a separate file 36 | * in this directory (for example: zone-flags.ts), and put the following flags 37 | * into that file, and then add the following code before importing zone.js. 38 | * import './zone-flags.ts'; 39 | * 40 | * The flags allowed in zone-flags.ts are listed here. 41 | * 42 | * The following flags will work for all browsers. 43 | * 44 | * (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame 45 | * (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick 46 | * (window as any).__zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames 47 | * 48 | * in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js 49 | * with the following flag, it will bypass `zone.js` patch for IE/Edge 50 | * 51 | * (window as any).__Zone_enable_cross_context_check = true; 52 | * 53 | */ 54 | 55 | /*************************************************************************************************** 56 | * Zone JS is required by default for Angular itself. 57 | */ 58 | import 'zone.js/dist/zone'; // Included with Angular CLI. 59 | 60 | 61 | /*************************************************************************************************** 62 | * APPLICATION IMPORTS 63 | */ 64 | -------------------------------------------------------------------------------- /src/styles.scss: -------------------------------------------------------------------------------- 1 | /* You can add global styles to this file, and also import other style files */ 2 | 3 | @import '~@angular/material/prebuilt-themes/indigo-pink.css'; 4 | 5 | html, 6 | body { 7 | height: 100%; 8 | } 9 | body { 10 | margin: 0; 11 | font-family: Roboto, 'Helvetica Neue', sans-serif; 12 | } 13 | 14 | .info { 15 | background-color: lightyellow; 16 | } 17 | 18 | -------------------------------------------------------------------------------- /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/dist/zone-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: any; 11 | 12 | // First, initialize the Angular testing environment. 13 | getTestBed().initTestEnvironment( 14 | BrowserDynamicTestingModule, 15 | platformBrowserDynamicTesting() 16 | ); 17 | // Then we find all the tests. 18 | const context = require.context('./', true, /\.spec\.ts$/); 19 | // And load the modules. 20 | context.keys().map(context); 21 | -------------------------------------------------------------------------------- /tsconfig.app.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "./out-tsc/app", 5 | "types": [] 6 | }, 7 | "files": [ 8 | "src/main.ts", 9 | "src/polyfills.ts" 10 | ], 11 | "include": [ 12 | "src/**/*.d.ts" 13 | ], 14 | "exclude": [ 15 | "src/test.ts", 16 | "src/**/*.spec.ts" 17 | ], 18 | "angularCompilerOptions": { 19 | "enableIvy": false 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compileOnSave": false, 3 | "compilerOptions": { 4 | "baseUrl": "./", 5 | "outDir": "./dist/out-tsc", 6 | "sourceMap": true, 7 | "declaration": false, 8 | "downlevelIteration": true, 9 | "experimentalDecorators": true, 10 | "module": "es2020", 11 | "moduleResolution": "node", 12 | "importHelpers": true, 13 | "target": "es5", 14 | "typeRoots": [ 15 | "node_modules/@types" 16 | ], 17 | "lib": [ 18 | "es2018", 19 | "dom" 20 | ] 21 | }, 22 | "angularCompilerOptions": { 23 | "fullTemplateTypeCheck": true, 24 | "strictInjectionParameters": true 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /tsconfig.spec.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "./out-tsc/spec", 5 | "types": [ 6 | "jasmine", 7 | "node" 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 | -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "tslint:recommended", 3 | "rules": { 4 | "align": { 5 | "options": [ 6 | "parameters", 7 | "statements" 8 | ] 9 | }, 10 | "array-type": false, 11 | "arrow-parens": false, 12 | "arrow-return-shorthand": true, 13 | "deprecation": { 14 | "severity": "warning" 15 | }, 16 | "component-class-suffix": true, 17 | "contextual-lifecycle": true, 18 | "curly": true, 19 | "directive-class-suffix": true, 20 | "directive-selector": [ 21 | true, 22 | "attribute", 23 | "app", 24 | "camelCase" 25 | ], 26 | "component-selector": [ 27 | true, 28 | "element", 29 | "app", 30 | "kebab-case" 31 | ], 32 | "eofline": true, 33 | "import-blacklist": [ 34 | true, 35 | "rxjs/Rx" 36 | ], 37 | "import-spacing": true, 38 | "indent": { 39 | "options": [ 40 | "spaces" 41 | ] 42 | }, 43 | "interface-name": false, 44 | "max-classes-per-file": false, 45 | "max-line-length": [ 46 | true, 47 | 140 48 | ], 49 | "member-access": false, 50 | "member-ordering": [ 51 | true, 52 | { 53 | "order": [ 54 | "static-field", 55 | "instance-field", 56 | "static-method", 57 | "instance-method" 58 | ] 59 | } 60 | ], 61 | "no-consecutive-blank-lines": false, 62 | "no-console": [ 63 | true, 64 | "debug", 65 | "info", 66 | "time", 67 | "timeEnd", 68 | "trace" 69 | ], 70 | "no-empty": false, 71 | "no-inferrable-types": [ 72 | true, 73 | "ignore-params" 74 | ], 75 | "no-non-null-assertion": true, 76 | "no-redundant-jsdoc": true, 77 | "no-switch-case-fall-through": true, 78 | "no-var-requires": false, 79 | "object-literal-key-quotes": [ 80 | true, 81 | "as-needed" 82 | ], 83 | "object-literal-sort-keys": false, 84 | "ordered-imports": false, 85 | "quotemark": [ 86 | true, 87 | "single" 88 | ], 89 | "trailing-comma": false, 90 | "no-conflicting-lifecycle": true, 91 | "no-host-metadata-property": true, 92 | "no-input-rename": true, 93 | "no-inputs-metadata-property": true, 94 | "no-output-native": true, 95 | "no-output-on-prefix": true, 96 | "no-output-rename": true, 97 | "semicolon": { 98 | "options": [ 99 | "always" 100 | ] 101 | }, 102 | "space-before-function-paren": { 103 | "options": { 104 | "anonymous": "never", 105 | "asyncArrow": "always", 106 | "constructor": "never", 107 | "method": "never", 108 | "named": "never" 109 | } 110 | }, 111 | "no-outputs-metadata-property": true, 112 | "template-banana-in-box": true, 113 | "template-no-negated-async": true, 114 | "typedef-whitespace": { 115 | "options": [ 116 | { 117 | "call-signature": "nospace", 118 | "index-signature": "nospace", 119 | "parameter": "nospace", 120 | "property-declaration": "nospace", 121 | "variable-declaration": "nospace" 122 | }, 123 | { 124 | "call-signature": "onespace", 125 | "index-signature": "onespace", 126 | "parameter": "onespace", 127 | "property-declaration": "onespace", 128 | "variable-declaration": "onespace" 129 | } 130 | ] 131 | }, 132 | "use-lifecycle-interface": true, 133 | "use-pipe-transform-interface": true, 134 | "variable-name": { 135 | "options": [ 136 | "ban-keywords", 137 | "check-format", 138 | "allow-pascal-case" 139 | ] 140 | }, 141 | "whitespace": { 142 | "options": [ 143 | "check-branch", 144 | "check-decl", 145 | "check-operator", 146 | "check-separator", 147 | "check-type", 148 | "check-typecast" 149 | ] 150 | } 151 | }, 152 | "rulesDirectory": [ 153 | "codelyzer" 154 | ] 155 | } --------------------------------------------------------------------------------