Skip to content

Instantly share code, notes, and snippets.

@mohamed-gara
Last active July 1, 2018 12:42
Show Gist options
  • Save mohamed-gara/b401cb500ba419a92717597bc5f217ca to your computer and use it in GitHub Desktop.
Save mohamed-gara/b401cb500ba419a92717597bc5f217ca to your computer and use it in GitHub Desktop.
change-detection-hell-loop
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