How Change Detection Works

Let's see how change detection works with a simple example.

We are going to create a simple MovieApp to show information about one movie. This app is going to consist of only two components: the MovieComponent that shows information about the movie and the AppComponent which holds a reference to the movie with buttons to perform some actions.

Our AppComponent will have three properties: the slogan of the app, the title of the movie and the lead actor. The last two properties will be passed to the MovieComponent element referenced in the template.

app/app.component.ts

  1. import {Component} from '@angular/core';
  2. import {MovieComponent} from './movie.component';
  3. import {Actor} from './actor.model';
  4. @Component({
  5. selector: 'app-root',
  6. template: `
  7. <h1>MovieApp</h1>
  8. <p>{{ slogan }}</p>
  9. <button type="button" (click)="changeActorProperties()">
  10. Change Actor Properties
  11. </button>
  12. <button type="button" (click)="changeActorObject()">
  13. Change Actor Object
  14. </button>
  15. <app-movie [title]="title" [actor]="actor"></app-movie>`
  16. })
  17. export class AppComponent {
  18. slogan = 'Just movie information';
  19. title = 'Terminator 1';
  20. actor = new Actor('Arnold', 'Schwarzenegger');
  21. changeActorProperties() {
  22. this.actor.firstName = 'Nicholas';
  23. this.actor.lastName = 'Cage';
  24. }
  25. changeActorObject() {
  26. this.actor = new Actor('Bruce', 'Willis');
  27. }
  28. }

In the above code snippet, we can see that our component defines two buttons that trigger different methods. The changeActorProperties will update the lead actor of the movie by directly changing the properties of the actor object. In contrast, the method changeActorObject will change the information of the actor by creating a completely new instance of the Actor class.

The Actor model is pretty straightforward, it is just a class that defines the firstName and the lastName of an actor.

app/actor.model.ts

  1. export class Actor {
  2. constructor(
  3. public firstName: string,
  4. public lastName: string) {}
  5. }

Finally, the MovieComponent shows the information provided by the AppComponent in its template.

app/movie.component.ts

  1. import { Component, Input } from '@angular/core';
  2. import { Actor } from './actor.model';
  3. @Component({
  4. selector: 'app-movie',
  5. template: `
  6. <div>
  7. <h3>{{ title }}</h3>
  8. <p>
  9. <label>Actor:</label>
  10. <span>{{actor.firstName}} {{actor.lastName}}</span>
  11. </p>
  12. </div>`
  13. })
  14. export class MovieComponent {
  15. @Input() title: string;
  16. @Input() actor: Actor;
  17. }

View Example

原文: https://angular-2-training-book.rangle.io/handout/change-detection/how_change_detection_works.html