Accessing Template Reference Variables from a view to another view

Viewed 128

Right now, I am working with a project that has a web design that will contain a multiple view (multiple HTML files) on a single page. Though this is not a new design, but I cannot find a solution for this.

What I am trying is to access the other element from another view, I know that after the view has been rendered, they will be a single HTML and not multiple, but the Angular syntax doesn't let me go through with this.

This is the sample code.

Let say I do have 2 files with names layout.html, header.html And also let say that the header has a selector named <app-header></app-header>

header.html

<div>
     <button (click)="sideBar.toggle()">
          <mat-icon>menu</mat-icon>
     </button>
</div>

layout.html

<div>
    <mat-toolbar>
        <app-header></app-header> <!-- important part -->
    </mat-toolbar>
    <mat-sidenav-container>
        <mat-sidenav #sideBar mode="side" opened> <!-- important part -->
            <app-sidebar></app-sidebar> 
        </mat-sidenav>
        <mat-sidenav-content>
            Main content
        </mat-sidenav-content>
    </mat-sidenav-container>
</div>

So I'm trying to toggle the <mat-sidenav> using the button on my header, and I am referencing it with #sideBar

Is this possible?

1 Answers

You can create an output in order to share information between component.

HeaderComponent.ts truncated file

import { Component, OnInit, Output, EventEmitter } from '@angular/core';

export class HeaderEvent {
    type: 'ToggleNavBar' | 'AnyOtherType';
    data: any;
}

 @Output() headerEvent: EventEmitter<HeaderEvent> = new EventEmitter();

 // Should be use on the (click) event of the button
 onToggle() : void {
     this.headerEvent.emit({type: 'ToggleNavBar', data: {}});
 }

HeaderComponent.html file

<div>
     <button (click)="onToggle()">
          <mat-icon>menu</mat-icon>
     </button>
</div>

layout.html file

<div>
    <mat-toolbar>
        <!-- Here you can listen the headerEvent event and do what you nee to do -->
        <app-header (headerEvent)="sideBar.toggle()"></app-header> 
    </mat-toolbar>
    <mat-sidenav-container>
        <mat-sidenav #sideBar mode="side" opened>
            <app-sidebar></app-sidebar> 
        </mat-sidenav>
        <mat-sidenav-content>
            Main content
        </mat-sidenav-content>
    </mat-sidenav-container>
</div>
Related