Andrea Bozza
Andrea Bozza

Reputation: 1384

ngOnInit() not called in a component dart with angular2

I have an app_component.dart that call this function

class OtherComponent {
  // ChromeCast receveiver event handler
  onLoad() { 
    this.router.navigate(["/Video", { 'pageData': pageData}]);
  }
}

To load another dart component called video_component.dart.

import 'package:angular2/angular2.dart';
import 'package:angular2/common.dart';
import 'package:angular2/router.dart';
import 'dart:js';
import 'dart:html';


@Component(selector: 'video-container', templateUrl: '../../views/video_component.html', directives: const [NgFor])
class VideoComponent implements OnInit {

  @Input()
  ContentService contentService;

  LoggerService log;

  String progress;

  RouteParams routeParams;

  var pageData;

  VideoComponent(@Inject(ContentService) this.contentService, @Inject(LoggerService) this.log, this.routeParams) {
    log.info('constructor called'); // <== constructor is called
  }

  @override
  ngOnInit() {
    log.info('ngOnInit:Load video page with content Id');
    //not called
  }
}

Why doesn't ngOnInit() not get called?

Upvotes: 2

Views: 814

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 658067

Try

NgZone zone;
ParentComponent(this.zone);

onLoad(event) {
  zone.run(() => this.router.navigate(...)
}

I assumed ParentComponent is the component that contains the event handler onLoad(event) ... and it's the constructor and used to inject NgZone like you did with ContentService and LoggerService in the code of your question. Change ParentComponent to the name of the class you use for this component.

The onLoad() from ChromeCast seems not to be patched from Angular and therefore doesn't run in Angulars zone. Now when the event handler is called from code outside Angulars zone some things don't work anymore (change detection for example).

With zone.run(...) we bring the context back to Angulars zone explicitely.

Upvotes: 2

Related Questions