我试图了解使用ChangeDetectionStrategy.OnPush的优势。所以在OnPush stategy可能有帮助的基本示例中写了一些组件。
Stackblits:https://stackblitz.com/edit/angular-stgymt
App Co html:
<h1>{{title}}</h1>
<button (click)="onClick()">Click</button>
<button (click)="changeTitle()">Change Title</button>
<app-movies
[movies]="movies"
></app-movies>
App Co ts:
title = 'app';
movies = [];
count = 0;
constructor() {
const movies = [];
for (let i = 0; i < 1000; i++) {
movies.push({
title: 'm' + i,
prop1: 1,
prop2: 1,
prop3: 1,
prop4: 1,
prop5: 1,
prop6: 1,
prop7: 1,
prop8: 1,
prop9: 1,
prop10: 1
});
}
this.movies = movies;
}
onClick() {
const mCopy = this.movies.slice(0);
mCopy.push({title: '10', elements: [1.9]});
this.movies = [...mCopy];
this.count++;
}
changeTitle() {
this.title = `${this.count}`;
this.count++;
}
电影公司:
<div *ngFor="let movie of movies">
<app-movie
[movie] = movie
></app-movie>
</div>
和Movie Co html:
<p>{{movie.title}}: </p>
<span>{{movie.prop1}}</span>
<span>{{movie.prop2}}</span>
<span>{{movie.prop3}}</span>
<span>{{movie.prop4}}</span>
<span>{{movie.prop5}}</span>
<span>{{movie.prop6}}</span>
<span>{{movie.prop7}}</span>
<span>{{movie.prop8}}</span>
<span>{{movie.prop9}}</span>
<span>{{movie.prop10}}</span>
OnDefault策略,如果我按钮改变标题,我期望的是电影组件,它的孩子也应该运行检测机制。但他们没有跑。这与OnPush完全相同。
我通过Chrome开发人员工具中的性能监视器检查了这两种情况,并且没有看到性能成就
那么使用OnPush策略有什么意义呢?
谢谢!