@Component({ selector: 'app-root', template: ` <h1>变更检测策略</h1> <p>{{ slogan }}</p> <button type="button" (click)="changeStar()"> 改变明星属性 </button> <button type="button" (click)="changeStarObject()"> 改变明星对象 </button> <movie [title]="title" [star]="star" [addCount]="count"></movie>`, }) export class AppComponent implements OnInit{ slogan: string = 'change detection'; title: string = 'OnPush 策略'; star: Star = new Star('周', '杰伦'); count:Observable<any>; ngOnInit(){ this.count = Observable.timer(0, 1000) } changeStar() { this.star.firstName = '吴'; this.star.lastName = '彦祖'; } changeStarObject() { this.star = new Star('刘', '德华'); } }
此时,有两种方式让MovieComponent进入检测,一种是使用变化检测对象中的 markForCheck()方法.
ngOnInit() { this.addCount.subscribe(() => { this.count++; this.changeRef.markForCheck(); })
另外一种是使用async pipe 管道
@Component({ selector: 'movie', styles: ['div {border: 1px solid black}'], template: ` <div> <h3>{{ title }}</h3> <p> <button (click)="changeStar()">点击切换名字</button> <label>Star:</label> <span>{{star.firstName}} {{star.lastName}}</span> </p> <p>{{addCount | async}}</p> </div>`, changeDetection: ChangeDetectionStrategy.OnPush })