Angular 8 @ViewChild返回未定义。无法访问元素参考



我正在尝试访问component模板中的元素。我添加了对元素的引用。我可以在模板中访问这些元素,但是在组件代码中,当我获得带有@ViewChild的引用时,它们会返回undefined.

这是我的模板代码。

<a #cartMenuButton class="nav-link cart-menu-button" (click)="cartMenuClick($event)">
<i class="fas fa-shopping-cart"></i>&nbsp;{{getCartCount()}}</a>

<div #cartMenuContainer class="cart-menu-container" (click)="cartMenuContainerClick($event)"
[style.display]="cartMenuVisible?'block':'none'">
<div #cartMenu class="cart-menu" [style.left.px]="cartMenuButton.offsetLeft-240"
[style.top.px]="cartMenuButton.offsetTop+cartMenuButton.offsetHeight">
<div class="cart-menu-items bg-light">
<ul class="list-group">
<app-cart-menu-item class="list-group-item bg-light" *ngFor="let item of sessionService.getCart()"
[item]="item">
</app-cart-menu-item>
</ul>
</div>
<div class="cart-menu-footer bg-dark">
<a routerLink="/cart" class="text-light float-left">Go to cart</a>
<a class="text-light float-right">Clear cart</a>
</div>
</div>
</div>

这是我的组件。

import { Component, ViewChild, ElementRef } from '@angular/core';
import { SessionService } from '../../../../services/session.service';
@Component({
selector: 'app-cart-menu',
templateUrl: 'cart-menu.component.html',
styleUrls: ['cart-menu.component.scss']
})
export class CartMenuComponent {
public cartMenuVisible: boolean = false;
@ViewChild('cartMenuButton', { read: Element, static: false })
public cartMenuButton: ElementRef;
@ViewChild('cartMenuContainer', { read: Element, static: false })
public cartMenuContainer: ElementRef;
constructor(public sessionService: SessionService) {
}
getCartCount(): number {
var count = this.sessionService.getCart() ? this.sessionService.getCart().reduce((acc, cur) => acc + cur.count, 0) : 0;
return count;
}
cartMenuClick(event: MouseEvent) {
this.cartMenuVisible = true;
}
cartMenuContainerClick(event: MouseEvent) {
if (event.currentTarget === this.cartMenuContainer.nativeElement)
this.cartMenuVisible = false;
}
}

cartMenuContainerClick函数中,它this.cartMenuContainer返回undefined

我在自己的应用程序中尝试了一些示例,这种组合似乎效果很好。

@ViewChild('cartMenuContainer', {static: false}) cartMenuContainer: ElementRef;

根据文档,将静态选项设置为true并不能保证所有可用元素都将加载以进行查询。

https://angular.io/guide/static-query-migration#how-do-i-choose-which-static-flag-value-to-use-true-or-false

尝试将static: true设置为查询结果将在ngOnInit中可用:

@ViewChild('cartMenuContainer', {static: true}) cartMenuContainer: ElementRef;

在 Angular 文档中有一篇关于查询的很棒的文章。

最新更新