浅谈Angular中的变化检测(Change Detection)


本文摘自PHP中文网,作者青灯夜游,侵删。

本篇文章我们来了解一下Angular中的变化检测(Change Detection)。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。

相关推荐:《angular教程》

ChangeDection

检测程序内部状态,然后反映到UI上。

引起状态变化,引发检查的驱动源:Events,XHR,Timers

ApplicationRef监听NgZone的onTurnDone,然后执行检测。

OnPush状态完全由外部决定,内部不会去更改状态。

例子:

聪明组件project-list变成OnPush检查策略,

在需要检测时候使用cd.markForCheck).

1

2

3

4

5

6

7

@Component({

  selector: "app-project-list",

  templateUrl: "./project-list.component.html",

  styleUrls: ["./project-list.component.scss"],

  animations:[

    slideToRight,listAnimation

  ],  changeDetection: ChangeDetectionStrategy.OnPush})

手动告诉Angualr你来检查我

在事件发生的时候主动告诉Angular来检查这条路线。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

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

1

2

3

4

@Component({

  selector: 'app-new-project',

  templateUrl: './new-project.component.html',

  styleUrls: ['./new-project.component.scss'],  changeDetection:ChangeDetectionStrategy.OnPush})

ChangeDetectorRef

1

2

3

4

5

6

7

8

9

10

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)的详细内容,更多文章请关注木庄网络博客

相关阅读 >>

Angular怎么刷新当前页面?方法介绍

Angular中关于单元测试的面试题,你能回答上来吗?

13个关于Angular的前端面试题(总结)

浅谈Angular控制器通信的4种方式

深入了解Angular中的pipe(管道)

Angular material的使用详解

Angular是什么

Angular如何创建服务?5种方式了解一下!

浅谈Angular cli的两种安装方式

浅谈Angular中父子组件相互传参的方法

更多相关阅读请进入《Angular》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...