lbpeppers lbpeppers - 4 years ago 267
TypeScript Question

What is the meaning of # inside an Angular2 HTML directive

I'm trying to trigger the state of the sidenav (opened and closed). I have this:

<div class="viewport">
<md-toolbar color="primary">
<button *ngIf="!isNavbarOpen" md-icon-button (click)="sidenav.open()"><md-icon>menu</md-icon></button>
<button *ngIf="isNavbarOpen" md-icon-button (click)="sidenav.close()"><md-icon>close</md-icon></button>
<span class="toolbar-title">Title</span>
</md-toolbar>
<md-sidenav-layout>
<md-sidenav align="start" mode="over" #sidenav>
Sidenav
</md-sidenav>
</md-sidenav-layout>
</div>


How can I use the #sidenav from my TypeScript file to change the isNavbarOpen field whenever the sidenav state changes?

or

How could I override the sidenav.open() method?

Answer Source

Here is a better approach so you can use all the properties and subscribe to all the events. Don't pass it to the open()/close() function.

<div class="viewport">
      <md-toolbar color="primary">
        <button *ngIf="!isNavbarOpen" md-icon-button (click)="open()"><md-icon>menu</md-icon></button>
        <button *ngIf="isNavbarOpen" md-icon-button (click)="close()"><md-icon>close</md-icon></button>
        <span class="toolbar-title">Title</span>
      </md-toolbar>
      <md-sidenav-layout>
        <md-sidenav align="start" mode="over" #sidenav>
          Sidenav
        </md-sidenav>
      </md-sidenav-layout>
    </div>

Instead references it by using "ViewChild" and MdSidenav:

import { Component, ViewChild, OnInit } from '@angular/core';
import { MdSidenav } from '@angular/material';

@Component({
....
})
export class AppComponent implements OnInit {
    public isNavbarOpen: boolean;

    // This gets a reference to the #sidenav
    @ViewChild('sidenav') sidenav: MdSidenav;

    ngOnInit() {
        // Subscribe to the onCloseStart event
        this.sidenav.onCloseStart.subscribe(() => {
            this.isNavbarOpen = true;
        });
    }

    open() {
       this.sideNav.open();
    }
 }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download