首頁  >  文章  >  web前端  >  淺談Angular中的變化偵測(Change Detection)

淺談Angular中的變化偵測(Change Detection)

青灯夜游
青灯夜游轉載
2021-02-22 17:48:241889瀏覽

本篇文章我們來了解一下Angular中的變化偵測(Change Detection)。有一定的參考價值,有需要的朋友可以參考一下,希望對大家有幫助。

淺談Angular中的變化偵測(Change Detection)

相關推薦:《angular教學

ChangeDection

偵測程式內部狀態,然後反映到UI。

造成狀態變化,引發檢查的驅動來源:Events,XHR,Timers

ApplicationRef監聽NgZone的onTurnDone,然後執行偵測。

OnPush狀態完全由外部決定,內部不會去更改狀態。

範例:

#聰明元件project-list變成OnPush檢查策略,

#在需要偵測時候用cd.markForCheck).

@Component({
  selector: "app-project-list",
  templateUrl: "./project-list.component.html",
  styleUrls: ["./project-list.component.scss"],
  animations:[
    slideToRight,listAnimation
  ],  changeDetection: ChangeDetectionStrategy.OnPush})

手動告訴Angualr你來檢查我

在事件發生的時候主動告訴Angular來檢查這條路線。

import { Component, OnInit , HostBinding, ChangeDetectionStrategy, ChangeDetectorRef } from "@angular/core";
import { MatDialog } from "@angular/material";
import { NewProjectComponent } from "../new-project/new-project.component";
import { InviteComponent } from '../invite/invite.component';
import { ConfirmDialogComponent } from '../../shared/confirm-dialog/confirm-dialog.component';
import {slideToRight} from '../../animate/router.animate'import { listAnimation } from '../../animate/list.animate';
import { projection } from '@angular/core/src/render3';

@Component({
  selector: "app-project-list",
  templateUrl: "./project-list.component.html",
  styleUrls: ["./project-list.component.scss"],
  animations:[
    slideToRight,listAnimation
  ],  changeDetection: ChangeDetectionStrategy.OnPush})
export class ProjectListComponent implements OnInit {
  @HostBinding('@routeAnim') state;

  projects = [
    {
      id:1,
      name: "企业协作平台",
      desc: "这是一个企业内部项目",
      coverImg: "assets/images/covers/0.jpg"
    },
    {
      id:2,
      name: "自动化测试项目",
      desc: "这是一个企业内部项目",
      coverImg: "assets/images/covers/2.jpg"
    }
  ];
  constructor(private dialog: MatDialog, private cd:ChangeDetectorRef) { }

  ngOnInit() { }

  openNewProjectDialog() {    // this.dialog.open(NewProjectComponent,{data:'this is a dialog'});
    const dialogRef = this.dialog.open(NewProjectComponent, {
      data: { title: '新建项目' }
    });
    dialogRef.afterClosed().subscribe((result) => {
      console.log(result);      this.projects = [...this.projects, 
        {id:3,name:'一个新项目',desc:'这是一个新项目',coverImg:"assets/images/covers/3.jpg"},
        {id:4,name:'又一个新项目',desc:'这是又一个新项目',coverImg:"assets/images/covers/4.jpg"}]
    });    this.cd.markForCheck();
  }

  lauchInviteDialog() {
    const dialogRef = this.dialog.open(InviteComponent);
  }

  lauchUpdateDialog() {
    const dialogRef = this.dialog.open(NewProjectComponent, {
      data: { title: '编辑项目' }
    });
  }

  lauchConfimDialog(project) {
    const dialogRef = this.dialog.open(ConfirmDialogComponent, {
      data: { title: '删除项目', content: '您确认删除该项目吗?' }
    });
    dialogRef.afterClosed().subscribe(result=>{
      console.log(result);      this.projects=this.projects.filter(p=>p.id!=project.id);      this.cd.markForCheck();
    });
  }
}

把笨組件標識為OnPush

直接加changeDetection:ChangeDetectionStrategy.OnPush

@Component({
  selector: 'app-new-project',
  templateUrl: './new-project.component.html',
  styleUrls: ['./new-project.component.scss'],  changeDetection:ChangeDetectionStrategy.OnPush})

ChangeDetectorRef

export abstract class ChangeDetectorRef {
  abstract markForCheck(): void;
  abstract detach(): void;
  abstract detectChanges(): void;
  abstract reattach(): void;
}<br>
markForCheck() - 当输入已更改或视图中发生了事件时,组件通常会标记为脏的(需要重新渲染)。调用此方法会确保即使那些触发器没有被触发,也仍然检查该组件。<br>在组件的 metadata 中如果设置了 changeDetection: ChangeDetectionStrategy.OnPush 条件,那么变化检测不会再次执行,除非手动调用该方法。
detach() - 从变化检测树中分离变化检测器,该组件的变化检测器将不再执行变化检测,除非手动调用 reattach() 方法。
reattach() - 重新添加已分离的变化检测器,使得该组件及其子组件都能执行变化检测
detectChanges() - 从该组件到各个子组件执行一次变化检测 检查该视图及其子视图。与 <a href="https://angular.cn/api/core/ChangeDetectorRef#detach">detach</a> 结合使用可以实现局部变更检测。

更多程式相關知識,請造訪: 程式設計入門! !

以上是淺談Angular中的變化偵測(Change Detection)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:cnblogs.com。如有侵權,請聯絡admin@php.cn刪除