Angular 2 ViewChild查询未在更改检测器之前运行

时间:2016-02-17 19:52:26

标签: javascript angular

我有一个带有一些ViewChild查询的Angular 2(beta 6)组件。它在一些向视图提供数据的方法中使用这些查询的结果(例如,测量元素的大小)。虽然在调用方法之前实际构造并添加元素,但查询尚未解析。

考虑这个组件(http://plnkr.co/edit/4RQPagQzrZISNDLpj2Ku):

var Cmp = ng.core.
  Component({
    selector: 'cmp',
    template: '<div class="parent" #parent>{{parentWidth()}}</div>',
    queries:{
      parent:new ng.core.ViewChild('parent')
    }
  }).
  Class({
    constructor: [ng.core.ElementRef, function Cmp(el) {
      this.el = el;
    }],
    parentWidth:function() {
      if(!this.parent) {
        console.warn('Change detector run before queries instantiated');
        console.warn('But note that the element exists', this.el.nativeElement.querySelector('.parent'));
        return 0;
      }
      return this.parent.nativeElement.offsetWidth;
    }
  });

document.addEventListener('DOMContentLoaded', function() {
  ng.platform.browser.bootstrap(Cmp);
});

parentWidth方法在实例化this.parent之前被调用,即使我想要访问的元素已经在DOM中。

是否有更好的方法可以从Javascript中查询元素,或者我是否应该在需要某些内容时再次使用this.el.querySelector('.parent')

2 个答案:

答案 0 :(得分:0)

等到

ngAfterViewInit() {
  this.parent... // parent is initialized 
} 

答案 1 :(得分:0)

不要调用方法表达式,而是试试这个:

<div class="parent" #parent>{{parent?.offsetWidth}}</div>