How can I access @ViewChild in another component from within a component?

Discussão em 'Angular' iniciado por Enes Ozmus, Janeiro 10, 2025.

  1. Enes Ozmus

    Enes Ozmus Guest

    The menu I want to open when the relevant button is clicked is inside a component. (SideBarCategoriesComponent)

    <div class="filters" #sideBar>
    ...
    ....
    .....
    ......
    </div>


    And the relevant button is in a different component.

    <div class="item-filter desktop-hide">
    <a href="#" class="filter-trigger label" (click)="toggleSidebarMenu()" #toggleButton>
    <i class="ri-menu-2-line ri-2x"></i>
    <span>Filter</span>
    </a>
    </div>

    export class ProductsComponent {
    @ViewChild('toggleButton') toggleButton: ElementRef = {} as ElementRef;

    constructor(private shopService: ShopService) {}

    toggleSidebarMenu() {
    this.shopService.toggleFilterMenu();
    }
    }


    I want the menu to close when clicking outside of the relevant menu and the relevant button.

    • The way I found to achieve this is to use @ViewChild.
    • But I can't access @ViewChild in another component from within a component.
    • So there are conflicts which break the workability.
    • How can I overcome this?

    export class SideBarCategoriesComponent {
    @HostBinding('class.active') filterMenu: boolean = false;
    @ViewChild('sideBar') sideBar: ElementRef = {} as ElementRef;

    constructor(private shopService: ShopService, private renderer: Renderer2) {
    this.renderer.listen('window', 'click', (e: Event) => {
    // I need the toggleButton @ViewChild here.
    if (
    e.target !== this.sideBar.nativeElement &&
    e.target !== this.toggleButton.nativeElement
    ) {
    this.shopService.filterMenu.set(false);
    }
    });
    }

    ngDoCheck() {
    this.filterMenu = this.shopService.filterMenu();
    }
    }

    Continue reading...

Compartilhe esta Página