Skip to content

Instantly share code, notes, and snippets.

@jhades
Last active December 18, 2020 11:50
Show Gist options
  • Save jhades/269ee42b83937418e0dbe00e49413342 to your computer and use it in GitHub Desktop.
Save jhades/269ee42b83937418e0dbe00e49413342 to your computer and use it in GitHub Desktop.
How does Angular 2 Change Detection Really Work ?
// this is the new version of addEventListener
function addEventListener(eventName, callback) {
// call the real addEventListener
callRealAddEventListener(eventName, function() {
// first call the original callback
callback(...);
// and then run Angular-specific functionality
var changed = angular.runChangeDetection();
if (changed) {
angular.reRenderUIPart();
}
});
}
@Component({
selector: 'todo-item',
template: `<span class="todo noselect"
(click)="onToggle()">{{todo.owner.firstname}} - {{todo.description}}
- completed: {{todo.completed}}</span>`
})
export class TodoItem {
@Input()
todo:Todo;
@Output()
toggle = new EventEmitter<Object>();
onToggle() {
this.toggle.emit(this.todo);
}
}
export class Todo {
constructor(public id: number,
public description: string,
public completed: boolean,
public owner: Owner) {
}
}
@Component({
selector: 'todo-list',
changeDetection: ChangeDetectionStrategy.OnPush,
template: ...
})
export class TodoList {
...
}
@Component({
selector: 'app',
template: `<div>
<todo-list [todos]="todos"></todo-list>
</div>
<button (click)="toggleFirst()">Toggle First Item</button>
<button (click)="addTodo()">Add Todo to List</button>`
})
export class App {
todos:Array = initialData;
constructor() {
}
toggleFirst() {
this.todos[0].completed = ! this.todos[0].completed;
}
addTodo() {
let newTodos = this.todos.slice(0);
newTodos.push( new Todo(1, "TODO 4",
false, new Owner("John", "Doe")));
this.todos = newTodos;
}
}
ngAfterViewChecked() {
if (this.callback && this.clicked) {
console.log("changing status ...");
this.callback(Math.random());
}
}
@NgModule({
declarations: [App],
imports: [BrowserModule],
bootstrap: [App]
})
export class AppModule {}
constructor(private ref: ChangeDetectorRef) {
ref.detach();
setInterval(() => {
this.ref.detectChanges();
}, 5000);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment