简体   繁体   English

Angular :是否可以让 Angular 指令(例如 NgIf 和 NgFor)仅在我想要的时候检查它们绑定到的变量?

[英]Angular : Is it possible to make Angular directives, such as NgIf and NgFor, check the variables to which they are binded only when I want to?

My Problem我的问题

From what I understand, Angular directives work by following the LifeCycleHook rhythm of the framework.据我了解,Angular 指令按照框架的 LifeCycleHook 节奏工作。
In other words, they are checked at certain times in the cycle, so that the related values are checked several times per second.换句话说,它们在循环中的特定时间被检查,因此相关值每秒检查数次。 However, I would have liked to know if it was possible to control these checks.但是,我想知道是否可以控制这些检查。


A situation一种情况

For example, let's imagine that I have an NgFor linked to an Array of 1000 objects.例如,假设我有一个 NgFor 链接到一个包含 1000 个对象的数组。
What will happen is that each object will be checked several times per second.将会发生的是,每个对象每秒都会被检查几次。 That's a few thousand checks per second.那是每秒几千张支票。
But that doesn't work for me.但这对我不起作用。 It's a lot more processing than I'd like.这比我想要的要多得多。

What I'm interested in is that my NgFor is checked only at the initialization of my page and during certain actions of the user.我感兴趣的是我的 NgFor 只在我的页面初始化和用户的某些操作期间检查。


My Question and What i've tried我的问题和我尝试过的

So my question is:所以我的问题是:

Is it possible to make the Angular directives, especially the NgIf and the NgFor, no longer perform checks following the rhythm of the LifeCycleHook and instead perform checks only when I want them to ?是否可以使 Angular 指令,尤其是 NgIf 和 NgFor 不再按照 LifeCycleHook 的节奏执行检查,而是仅在我希望它们时执行检查? Or do I have to do this using pure HTML/CSS/Javascript methods ?还是我必须使用纯 HTML/CSS/Javascript 方法来做到这一点?

To solve this problem, I've already looked into TrackBy.为了解决这个问题,我已经研究了 TrackBy。 However, this does not change the heart of the problem.然而,这并不能改变问题的核心。
It will still be a few thousand checks that will be performed.仍将执行几千次检查。 Except that they will be checks of values and not of objects.除了它们将检查值而不是对象。

Have you tried using ChangeDetectionStrategy.OnPush?您是否尝试过使用 ChangeDetectionStrategy.OnPush?

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.html',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class MyComponent implements OnInit {
  constructor(private changeDetector: ChangeDetectorRef) {
  }

  prop1: string;
  prop2: string;

  someMethod(): void {
    prop1 = 'abc';
    // *ngIf won't be checked yet
    prop2 = 'xyz';
    // nor here
    this.changeDetector.detectChanges();
    // now it will

  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM