gpt4 book ai didi

javascript - Angular 2 ViewChild 查询在更改检测器之前不运行

转载 作者:行者123 更新时间:2023-11-28 06:21:46 25 4
gpt4 key购买 nike

我有一个 Angular 2(beta 6)组件,其中包含一些 ViewChild 查询。它在向 View 提供数据的某些方法中使用这些查询的结果(例如测量元素的大小)。虽然在调用方法之前元素实际上已构建并添加到 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);
});

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

是否有更好的方法从 Javascript 查询元素,或者每当我需要 View 中的某些内容时我应该返回使用 this.el.querySelector('.parent')

最佳答案

等到

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

关于javascript - Angular 2 ViewChild 查询在更改检测器之前不运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35466402/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com