2
votes

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. Here is a minimal example:

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

  }
}

My expectation was that the detached component's view would be updated every 3 seconds with fresh internal values. 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.

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

So the question is: how to detach a component from change detection and manually trigger it on certain events?

2

2 Answers

1
votes

You need to attache before running change detection

  • re-attach
  • markForCheck()
  • detach
0
votes

using OnPush strategy and markforCheck()

This is the common way to trigger change detection manually