使用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
列表是每秒用新值创建的,我每3秒运行一次detectChanges()
,但屏幕上没有任何变化。
我也尝试过的事情:
OnPush
策略和markforCheck()
而不是detectChanges()
-按预期工作所以问题是:如何从变更检测中分离组件并在某些事件上手动触发它?
答案 0 :(得分:1)
您需要先附加附件,然后才能运行更改检测
markForCheck()
答案 1 :(得分:0)
使用
OnPush
策略和markforCheck()
这是手动触发变更检测的常用方法