脏值检测原理

1 入门

脏值检测(Change Detection)

脏值检测的基本原理是存储旧数值,并在进行检测时,把当前时刻的新值和旧值比对。若相等则没有变化,反之则检测到变化,需要更新视图。

Angular有两种策略:Default和OnPush

NgFor

多数情况下,NgFor应该伴随trackBy方程使用。否则,每次脏值检测过程中,NgFor会把列表里每一项都执行更新DOM操作。

@Component({
 selector: 'my-app',
 template: `
  <ul>
   <li *ngFor="let item of collection;trackBy: trackByFn">{{item.id}}</li>
  </ul>
  <button (click)="getItems()">Refresh items</button>
 `,
})
export class App {
 collection;
 constructor() {
  this.collection = [{id: 1}, {id: 2}, {id: 3}];
 }
  
 getItems() {
  this.collection = this.getItemsFromServer();
 }
  
 getItemsFromServer() {
  return [{id: 1}, {id: 2}, {id: 3}, {id: 4}];
 }
  
 trackByFn(index, item) {
  return index;
 }
}

NgFor使用

使用指南

2 检查策略

使用

import { Component, OnInit, ViewEncapsulation, ChangeDetectionStrategy, Input, ChangeDetectorRef } from '@angular/core';

@Component({
  selector: 'scm-side-menu',
  templateUrl: './side-menu.component.html',
  styleUrls: ['./side-menu.component.scss'],
  encapsulation: ViewEncapsulation.None, // 增加该元数据则会让该组件的样式应用到整个app
  changeDetection: ChangeDetectionStrategy.OnPush
})

constructor(
  private cd:ChangeDetectorRef) { }

public data = []; // 此data已在页面绑定html
public clickBtn(item){
  this.data.push(item);
  this.data = JSON.parse(JSON.stringify(this.data)); // clone数组
  this.cd.detectChanges(); // 在需要更新视图时手动触发ng的检测
}

Angular有两种策略:Default和OnPush

Default:

  优点: 每一次有异步事件发生,Angular都会触发变更检测(脏检查),从根组件开始遍历其子组件,对每一个组件都进行变更检测,对dom进行更新
  缺点: 有很多组件状态(state)没有发生变化,无需进行变更检测,进行没有必要的变更检测,如果你的应用程序中组件越多,性能问题会越来越明显.

Onpush:

  优点: 组件的变更检测(脏检查)完全依赖于组件的输入(@Input),只要输入值不变,就不会触发变更检测,也不会对其子组件进行变更检测,在组件很多的时候会有明显的性能提升
  缺点:必须保证输入(@Input)是不可变的(可以用Immutable.js解决),就是每一次输入变化都必须是一个新的引用(js中object,array的可变性).

Onpush策略

Onpush教程

使用

  • markForCheckOnPush 而生,它就是专门配合 OnPush 策略的,在 Default 策略下没有使用意义。
  • markForCheck 只是从当前组件向上移动到跟组件并在移动的同时,将组件状态更新为 ChecksEnabled

变化检测

演示

test.component.ts

import {Component,OnInit,Input,Output,EventEmitter,ChangeDetectionStrategy,ChangeDetectorRef} from '@angular/core';
@Component({
  selector: 'test-binding',
  template: `
  <div *ngFor="let ball of balls">{{ball}}</div>`,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class TestDataBindingComponent implements OnInit{
  @Input() balls: any[];
  constructor(
    private cd: ChangeDetectorRef
  ){}
  ngOnInit(){
    setTimeout(() => {
      this.balls.push('new ball');
    },2000)
  }
  
  refresh(){
    console.log(this.balls);
    setTimeout(() => {
      this.cd.detectChanges();
      //this.cd.markForCheck();
    },5000)
  }
}

app.component.ts

import { Component,OnInit,ViewChild } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
  balls: any[] = ['basketball','football'];
  @ViewChild('test') test;
  ngOnInit(){
    
  }
  
  addBall(ball){
    this.balls.push(ball);
    this.test.refresh();
  }
  changeRef(){
    this.balls = ['baseball','pingpong'];
  }
}

app.component.html

<test-binding #test [balls]="balls"></test-binding>

<br>
<br>
<input #input>
<button (click)="addBall(input.value)">Add a ball</button>
<br>
<br>
<button (click)="changeRef()">Change Ref</button>

//css
p {
  font-family: Lato;
}

变化策略

default策略

//组件遍历检测

变更检测策略

ngif使用

带有 “else” 块的格式:

<div *ngIf="condition; else elseBlock">Content to render when condition is true.</div>
<ng-template #elseBlock>Content to render when condition is false.</ng-template>

带 “then” 和 “else” 块的简写形式:

<div *ngIf="condition; then thenBlock else elseBlock"></div>
<ng-template #thenBlock>Content to render when condition is true.</ng-template>
<ng-template #elseBlock>Content to render when condition is false.</ng-template>

展开例子

@Component({
  selector: 'ng-if-simple',
  template: `
    <button (click)="show = !show">{{show ? 'hide' : 'show'}}</button>
    show = {{show}}
    <br>
    <div *ngIf="show">Text to show</div>
`
})
export class NgIfSimple {
  show = true;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值