dart - Angular2:从模板访问子节点

标签 dart angular future web-component angular-dart

我有一个组件,我想从模板访问一些子节点。我可以访问details div,但是我不知道为什么代码可以工作。 Future class到底是什么?为什么第一行打印为空?这是从模板访问子节点的正确方法吗?

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

最佳答案

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

关于dart - Angular2:从模板访问子节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35961815/

相关文章:

svg - 鼠标悬停在矩形边框上

dart - 如果列表中不包含对象,则将其添加到列表中

javascript - 将点击事件绑定(bind)到 Kendo ToolBar

angular - 理解 Gradle "task"语法

dart - 为什么 cupertino_icons 中的图标很少?

flutter - 云 Firestore : Best way to get collection with nested element references

javascript - 使 angular2-cookie 安全并加密

dart - 错误 : The argument type '(File) → Future<dynamic>' can't be assigned to the parameter type '(dynamic) → FutureOr<dynamic>'

Scala Future 用于理解 : sequential vs parallel

scala - 如何处理 Play Controller 中的 AskTimeoutException