简体   繁体   English

分离组件的角度手动更改检测

[英]Angular manual change detection for detached components

Using Angular Dart 5.2, I'm trying to explore how to detach a component from change detection and do manual checking, but could not succeed.使用 Angular Dart 5.2,我试图探索如何从变更检测中分离组件并进行手动检查,但未能成功。 Here is a minimal example:这是一个最小的例子:

app_component.dart app_component.dart

import 'package:angular/angular.dart';
import 'package:angular_change_detection/detached.dart';

@Component(
  selector: 'my-app',
  template: '''
    <h1>Angular change detection tests</h1>
    <detached></detached>
  ''',
  directives: [DetachedComponent],
)
class AppComponent {}

detached.dart分离.dart

import 'dart:async';
import 'dart:math' show Random;

import 'package:angular/angular.dart';

@Component(
  selector: 'detached',
  template: '''
    <span *ngFor="let i of internal">{{i}}, </span>
  ''',
  directives: [coreDirectives],
  changeDetection: ChangeDetectionStrategy.Detached
)
class DetachedComponent implements OnInit {
  final Random random = Random();
  final ChangeDetectorRef changeDetectorRef;

  List<int> internal = [];

  DetachedComponent(this.changeDetectorRef);

  @override
  void ngOnInit() {
    Timer.periodic(Duration(seconds: 1), (_) {
      internal = List.generate(random.nextInt(10) + 1, (i) => (DateTime.now().millisecondsSinceEpoch * (i + 1)) % 1337);
      print("Internal list changed: $internal}");
    });

    Timer.periodic(Duration(seconds: 3), (_) {
      changeDetectorRef.detectChanges();
      print("detecting changes; internal list reference: ${internal.hashCode}");
    });

  }
}

My expectation was that the detached component's view would be updated every 3 seconds with fresh internal values.我的期望是分离组件的视图将每 3 秒用新的internal值更新一次。 The console log reflects that internal List is newly created every second with new values, and I run detectChanges() every 3 seconds, but nothing changes on screen.控制台日志反映internal List 每秒都用新值新创建,我每 3 秒运行一次detectChanges() ,但屏幕上没有任何变化。

Things I've also tried:我也尝试过的事情:

  • manually detaching the component from change detection from the constructor - nothing changed从构造函数的更改检测中手动分离组件 - 没有任何改变
  • using OnPush strategy and markforCheck() instead of detectChanges() - worked as expected使用OnPush策略和markforCheck()而不是detectChanges() - 按预期工作

So the question is: how to detach a component from change detection and manually trigger it on certain events?所以问题是:如何从更改检测中分离组件并在某些事件上手动触发它?

You need to attache before running change detection您需要在运行更改检测之前附加

  • re-attach重新连接
  • markForCheck()
  • detach分离

using OnPush strategy and markforCheck()使用OnPush策略和markforCheck()

This is the common way to trigger change detection manually这是手动触发更改检测的常用方法

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

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