Angular 8 @ViewChild возвращает неопределенное значение. Не могу получить доступ к ElementRef - PullRequest
1 голос
/ 15 октября 2019

Я пытаюсь получить доступ к элементам в моем шаблоне в 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.

Ответы [ 2 ]

0 голосов
/ 15 октября 2019

Я попробовал несколько примеров в своем собственном приложении, и эта комбинация, кажется, работает хорошо.

@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

0 голосов
/ 15 октября 2019

Попробуйте установить static: true, так как результаты запроса будут доступны в ngOnInit:

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

В документации Angular есть отличная статья о запросе.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...