To create different components, use the following syntax.
This will create the component. I am going to create three different components as home, blogs, & contact.
In the home component, I am going to write some HTML code which contains logo & menu list.
In blog & contact, I am going to write just a welcome message to the blog page.
Step 2
In home.component.html, write the below code.
- <div style="text-align:Left">
- <img width="200" alt="CodderFunda Logo" src="http://coderfunda.com/wp-content/uploads/2018/02/logo2.png">
- </div>
- <h4>Here are sample menu items </h4>
- <ul>
- <li><a routerLink="#home">Home</a></li>
- <li><a routerLink="/blogs">Latest Blogs</a></li>
- <li><a routerLink="/events">Events</a></li>
- <li><a routerLink="/contact">Contact</a></li>
- </ul>
The
routerLink directives on the anchor tags give the router control over those elements. The navigation paths are fixed.
Step 3
In app.component.html, write your selector & we are going to use routing as below.
- <app-home></app-home>
- <router-outlet></router-outlet>
<router-outlet> is used to specify which comopnent should load. Suppose you are going to access URL localhost:1234/blogs then router matches that URL to route path /blogs and displays the content from blogs.component.html to View.
Step 4
Now, you have to import components into an app.module.ts file as shown in below. Also, specify the entry of each address bar path and the component to render into the router-outlet.
- import { BrowserModule } from '@angular/platform-browser';
- import { NgModule } from '@angular/core';
-
- import { AppComponent } from './app.component';
- import { RouterModule } from '@angular/router';
- import { HomeComponent } from './Component/home/home.component';
- import { BlogsComponent } from './Component/blogs/blogs.component';
- import { enableProdMode } from '@angular/core';
- import { ContactComponent } from './Component/contact/contact.component';
- import { EventsComponent } from './Component/events/events.component';
-
- @NgModule({
- declarations: [
- AppComponent,
- HomeComponent,
- BlogsComponent,
- ContactComponent,
- EventsComponent
- ],
- imports: [
- BrowserModule,
- RouterModule.forRoot([
- { path: 'blogs', component: BlogsComponent },
- { path: 'contact', component: ContactComponent },
- { path: 'events', component: EventsComponent }
- ])
- ],
- providers: [],
- bootstrap: [AppComponent]
- })
- export class AppModule { }
Step 5
Now, run the application by using the below command.