Angular 分离组件的手动更改检测

Angular manual change detection for detached components

使用 Angular Dart 5.2,我试图探索如何从变更检测中分离组件并进行手动检查,但未能成功。这是一个最小的例子:

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

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}");
    });

  }
}

我的期望是分离组件的视图每 3 秒更新一次 internal 新值。控制台日志反映 internal List 每秒用新值创建一次,我每 3 秒 运行 detectChanges(),但屏幕上没有任何变化。

我也尝试过的事情:

所以问题是:如何从变化检测中分离组件并在某些事件上手动触发它?

using OnPush strategy and markforCheck()

这是手动触发变化检测的常用方法

您需要在 运行 更改检测之前附加

  • 重新附加
  • markForCheck()
  • 分离