javascript - 如何访问 ngOnInit 上的 nativeElements?

标签 javascript angular

假设在我的 Angular 代码中,我可以通过 viewChild('someDiv')constructor(private elem: ElementRef){} 访问 html 元素。每当我的 Angular 组件被加载我想访问该元素的一些属性,以便我可以将其存储在变量中。例如-我想在该组件加载后立即获取元素宽度,所以我的代码是

@ViewChild('someDiv') someDiv: ElementRef;
someDivWidth;
ngOnInit(){
 someDivWidth = this.someDiv.nativeElement.clientWidth;
}

和我的 html 代码

<div #someDiv>some text</div>

但是这给出了像nativeElement is undefined这样的错误。那么我该如何解决这个问题呢?我的基本需求是一旦这个组件加载,我想在变量中设置div的宽度而不触发 任何功能。

更新:

因此,使用 constructor(private elem: ElementRef){} 不会给出任何错误,我可以通过以下方式访问宽度

ngOnInit(){
 this.someDivWidth = this.elem.nativeElement.querySelector('.someCssSelector');
}

但是假设我有一些产品数据,我从后端获取这些数据并将其存储在 ngOnInit 生命周期 Hook 中的数组中,并在我的模板中根据使用生命周期 Hook 的产品数据数组创建多个 div。在这种情况下,如果我想获取目前我正在做的所有产品 div 都像

products = [];
items;
ngOnInit(){
 this.productService.getProducts().subscribe(products => {
  this.products = products 
 })
 this.itmes = this.elem.nativeElement.querySelectorAll('.each-product');
 console.log(this.items)
}

这给了我一个空的节点列表。我在设置 this.items 时想到,我的产品不会从后端加载,这就是为什么它给我空数组或节点列表,但将最后两行放在 subscribe() 中,例如

ngOnInit(){
 this.productService.getProducts().subscribe(products => {
  this.products = products 
  this.itmes = this.elem.nativeElement.querySelectorAll('.each-product');
  console.log(this.items)
 })
}

我的html代码是

<div>
 <div *ngFor='let product of products' class='each-product'>...</div>
</div>

仍然给我一个空数组或节点列表。该怎么办?

最佳答案

您应该在 Angular 生命周期的 ngAfterViewInit 方法中执行此操作。

 ngAfterViewInit(){
             this.someDivWidth = this.elem.nativeElement.querySelector('.someCssSelector');
    }

关于javascript - 如何访问 ngOnInit 上的 nativeElements?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64084048/

相关文章:

javascript - Chrome 应用程序 : How to create a hovering circle icon like google hangout app?

javascript - AngularJS 将对象添加到数组会更新所有相似的对象

javascript: window.open 抛出无效 url 错误

css - ionic 3 动态主题化应用程序

angular - 是否有类似于 withLatestFrom 但带有参数的 RxJS 运算符?

html - [null] 中未定义的错误 _renderer.setElementStyle "Cannot set property ' 背景颜色'

javascript - 无法触发 Drum Machine 项目中的元素 (React)

javascript:在创建的div中的h1中显示提示文本

angular - Electron:如何解析产品中的 CSS url?

Angular 错误: The left-hand side of an assignment expression must be a variable or a property access