aliemre
aliemre

Reputation: 129

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

I am trying to access elements in my template in component. I added references to elements. I can access these elements inside template but in component code when I get references with @ViewChild they return undefined.

Here is my template code.

<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>

Here is my component.

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;
    }
}

In cartMenuContainerClick function it this.cartMenuContainer returns undefined.

Upvotes: 3

Views: 6381

Answers (2)

Damian C
Damian C

Reputation: 2171

I tried a few examples in my own app, and this combination seems to work well.

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

According to the documentation, setting the static option to true does not guarantee all available elements will loaded for querying.

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

Upvotes: 3

StepUp
StepUp

Reputation: 38154

Try to set static: true as query results will be available in ngOnInit:

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

There is a great article about query in Angular documentation.

Upvotes: 0

Related Questions