Angular2: Accessing child nodes from a template

Issue

I have a component and I would like accessing some child nodes from the template. I achieved to access the details div, but I don’t know why the code works. What exactly does the Future class? And why the first line prints null? Is this the correct way to access child nodes from the template?

@Component(selector: 'hero-detail', template: '<div #details></div>')
class HeroDetailComponent implements OnInit {
  Hero hero;

  @ViewChild('details')
  var details;

  Future ngOnInit() async {
    // why this command prints null?
    print(details);
    // why this command prints "Instance of 'ElementRef_'"
    new Future(() => print(details));
  }
}

Solution

@Component(selector: 'hero-detail', template: '<div #details></div>')
class HeroDetailComponent implements OnInit {
  Hero hero;


  // Angular generates additional code that looks up the element 
  // from the template that has a template variable `#details
  // and assigns it to `var details`
  @ViewChild('details')
  var details;

  // I don't think Future does anything here.
  Future ngOnInit() async {
    // why this command prints null?

    // this is too early. `@ViewChild()` is only set in `ngAfterViewInit`
    // at this point the view is not yet fully created and therefore
    // `#details can't have been looked up yet
    print(details);
    // why this command prints "Instance of 'ElementRef_'"

    // this delays `print(details)` until the next Dart event loop
    // and `details` is then already lookup up and assigned
    new Future(() => print(details));
  }

  // this is the right place
  // needs `class HeroDetailComponent implements OnInit, AfterViewInit {
  ngAfterViewInit() {
    print(details);
  }
}

Answered By – Günter Zöchbauer

Answer Checked By – David Marino (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.