繁体   English   中英

Angular 8 @ViewChild 返回未定义。 无法访问 ElementRef

[英]Angular 8 @ViewChild returns undefined. Can't access ElementRef

我正在尝试访问组件中模板中的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 function 中this.cartMenuContainer返回undefined

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

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

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM