我正在尝试访问component
中模板中的元素。我添加了对元素的引用。我可以在模板中访问这些元素,但是当我使用@ViewChild
获得引用时,它们会在组件代码中返回undefined
。
这是我的模板代码。
<a #cartMenuButton class="nav-link cart-menu-button" (click)="cartMenuClick($event)">
<i class="fas fa-shopping-cart"></i> {{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
。
答案 0 :(得分:0)
尝试设置static: true
,因为查询结果将在ngOnInit
中显示:
@ViewChild('cartMenuContainer', {static: true}) cartMenuContainer: ElementRef;
There is a great article about query in Angular documentation.
答案 1 :(得分:0)
我在自己的应用中尝试了一些示例,这种组合似乎效果很好。
@ViewChild('cartMenuContainer', {static: false}) cartMenuContainer: ElementRef;
根据文档,将 static 选项设置为 true 不能保证将加载所有可用元素以进行查询。