SideNav component

In a similar manner, let's now create a component for the left-hand side navigation panel, as follows:

ng generate component sidenav  

This will create three source files in the app/sidenav directory as we have seen before, and register our component by modifying the app.module.ts file. The sidenav.component.html file is again a simple cut and paste from our existing HTML file, as follows:

<div id="mySidenav" class="sidenav"> 
  <a href="#">About</a> 
  <a href="#">Services</a> 
  <a href="#">Clients</a> 
  <a href="#">Contact</a> 
</div> 

The auto-generated SideNavComponent class needs to be updated with two new functions, as follows:

import { Component } from '@angular/core'; 
 
@Component( { 
    selector: 'app-sidenav', 
    templateUrl: './sidenav.component.html', 
    styleUrls: ['./sidenav.component.css'] 
}) 
 
export class SideNavComponent { 
 
    closeNav() { 
        document.getElementById('mySidenav') 
            .style.width = "0px"; 
    } 
     
    showNav() { 
        document.getElementById('mySidenav') 
            .style.width = "250px"; 
    } 
 
} 

Here, we have created two functions in this class, named closeNav and showNav. These two functions set the style.width CSS property to 0px and 250px, respectively. What we have done here is to essentially encapsulate all of the functionality surrounding the side navigation bar into the SideNavComponent class. This is the single responsibility design principle – that states a class should just have a single responsibility.

We will also need to remove the css from the app.component.css file that applies to this sidenav bar, and drop it into the sidenav.component.css file. This is an example of encapsulation. The sidenav component has everything that it needs, including styles, HTML templates, tests and code encapsulated into a single element.

We can now drop in the <app-sidenav> tag into our app.component.html file.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.184.214