angular8 脏值检查

什么是脏值检查?

当数据改变时更新视图(DOM)

什么时候会触发脏值检查?

浏览器事件(如click,mouseover,keyup等)

setTimeout()和setInterval()

HTTP请求

如何进行检测

检查两个状态值:当前状态和新状态

 

 

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

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
 
  _title;
  public get title() : string {
    console.log("脏值检测")
    return this._title;
  }

  constructor(private ngZone : NgZone ) { 
    this._title = "hi"
  }


  ngOnInit() {
  }
  ngAfterViewChecked(): void {
    //Called after every check of the component's view. Applies to components only.
    //Add 'implements AfterViewChecked' to the class.
    this.ngZone.runOutsideAngular(()=>{
      setInterval(()=>{
        this._title = "您好"
      },100)
    })
  }

}

 

import { Component, OnInit, NgZone, ViewChild, Renderer2 } from '@angular/core';
import { formatDate } from '@angular/common';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
 _time;
 @ViewChild("timeRef",{static:true}) timeRef:Element;
  public get time() : number {
    return this._time;
  }
  constructor(private ngZone : NgZone,private rd2:Renderer2 ) { 
  }
  ngOnInit() {
  }
  ngAfterViewChecked(): void {
    //Called after every check of the component's view. Applies to components only.
    //Add 'implements AfterViewChecked' to the class.
    this.ngZone.runOutsideAngular(()=>{
      setInterval(()=>{
        this.rd2.setProperty(
          this.timeRef.nativeElement,
          'innerText',
          formatDate(Date.now(),'HH:mm:ss:SSS','ZH-Hans'))
      },100)
    })
  }
  handleClick(){
      
  }
}

如果报下面的错的话 

angular8 脏值检查_第1张图片

 

import { registerLocaleData } from '@angular/common';

import zh from '@angular/common/locales/zh';

registerLocaleData(zh);

 

在@component中添加

changeDetection:ChangeDetectionStrategy.OnPush

如果遇到路由传参的话  调到其他页面  再跳回来的话跳不回来

constructor(private cd:ChangeDetectorRef) { }
 ngOnInit() {
    this.route.paramMap.subscribe(params => {
      this.selectedTabLink = params.get('tabLink')
      this.cd.markForCheck();
    })
    this.channels = this.service.getChannels()
    this.imageSliders = this.service.getImageSliders()
  }

 

你可能感兴趣的:(angular8)