Last active
July 1, 2018 12:42
-
-
Save mohamed-gara/b401cb500ba419a92717597bc5f217ca to your computer and use it in GitHub Desktop.
change-detection-hell-loop
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Component, DoCheck } from '@angular/core'; | |
@Component({ | |
selector: 'app', | |
template: ` | |
<h3>Change detection hell loop</h3> | |
<div>Counter: {{ counter }}</div> | |
<div> | |
<button (click)="increment()">Increment</button> | |
<button (click)="decrement()">Decrement</button> | |
</div>`, | |
styleUrls: [ './app.component.css' ] | |
}) | |
export class AppComponent implements DoCheck { | |
counter = 0; | |
resolvedPromise = Promise.resolve(null) | |
ttl = 5; | |
increment() { | |
this.counter++; | |
} | |
decrement() { | |
this.counter--; | |
} | |
ngDoCheck() { | |
console.log('Angular change detection cycle is running.'); | |
if (--this.ttl === 0) { | |
console.error('CD is triggred five times... Stop the hell loop...'); | |
return; | |
} | |
this.resolvedPromise | |
.then( | |
() => console.log(`This is a microtask scheduled during change detection phase...`) | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment