【问题标题】:Angular 2 ViewChild queries not run before change detectorAngular 2 ViewChild 查询未在更改检测器之前运行
【发布时间】:2016-02-17 19:52:25
【问题描述】:

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

考虑这个组件 (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')

【问题讨论】:

  • 我在 plunkr 控制台中遇到错误..?您在向问题添加 plunkr 时是否遗漏了什么?
  • 不,错误是因为我描述的行为。请注意,在控制台中,您会收到我的两个控制台警告,然后是一些 Angular 错误,即 parentWidth 的值已从 0 更改为其他值。

标签: javascript angular


【解决方案1】:

等到

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

【讨论】:

  • 我不能等到视图初始化之后,因为方法是从视图本身调用的。
  • 看起来没有必要,如果不等到视图准备好,将无法正常工作。
  • 您如何建议让元素显示自己的尺寸,或者根据自己的尺寸以复杂的方式计算出来的东西?
  • 读取ngAfterViewInit()中的维度并将其分配给变量并将视图绑定到变量而不是函数。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2017-09-18
    • 2021-06-14
    • 2016-03-26
    • 2017-07-09
    • 2019-09-26
    • 1970-01-01
    • 2019-01-22
    • 2017-01-08
    • 2019-07-28
    相关资源
    最近更新 更多