Navbar component

Our first task is to create a NavbarComponent class that will have the sole responsibility of rendering the navigation bar at the top of the screen. To do this, we will create a navbar.component.ts file and a navbar.component.html file in our app directory. This can easily be accomplished using the Angular-CLI, by executing the following on the command line:

ng generate component navbar  

This command will create a new directory in the src/app folder, and generate the necessary files for our new component, including the main .ts file, a .css file, an .html file, as well as a .spec.ts file for testing. It will also generate standard code for creating the component, as well as modifying the app.module.ts file to automatically make this component available for use.

The contents of the navbar.component.html file can be simply copied from our existing app.component.html file, as follows:

<nav class=" navbar navbar-inverse bg-inverse  
navbar-toggleable-sm"> 
    <a class="navbar-brand">&nbsp;</a> 
    <div class="nav navbar-nav"> 
        <a class="nav-item nav-link active">Home</a> 
        <a class="nav-item nav-link">Products</a> 
        <a class="nav-item nav-link">About Us</a> 
    </div> 
</nav> 

The Angular-CLI will have created the NavbarComponent class for us, as follows:

import { Component, OnInit } from '@angular/core'; 
 
@Component({ 
  selector: 'app-navbar', 
  templateUrl: './navbar.component.html', 
  styleUrls: ['./navbar.component.css'] 
}) 
export class NavbarComponent implements OnInit { 
 
  constructor() { } 
 
  ngOnInit() { 
  } 
 
} 

This is a very basic Angular class that references our HTML file, and specifies a selector property in the @Component decorator. To use this new component in our application, we will simply drop in a <app-navbar> tag in our current app.component.html file.

Note that the Angular-CLI has modified the app.module.ts file to register the component for us, as follows:

import { AppComponent } from './app.component'; 
import { NavbarComponent } from './navbar/navbar.component'; 
 
@NgModule({ 
  declarations: [ 
    AppComponent, 
    NavbarComponent 
  ], 
  imports: [ 
    BrowserModule 
  ], 
  providers: [], 
  bootstrap: [AppComponent]}) 

Note the module import statement that references our navbar.component module, and the updated declarations array of the @NgModule decorator. By updating the declarations array, the <app-navbar> tag will be made available for use within any HTML template.

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

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