Angular 5 and 4 Routing Steps -
ü Steps 1 - Create a component
ü Steps 2 - Import RouterModule in @NgModule
import {RouterModule} from '@angular/router';
ü Steps 3 - Create the root path and component in the @NgModule
imports: [
BrowserModule,
RouterModule.forRoot([{ //Added Router Module root path and component
path:'web-link',
component: UserComponent
}
])
]
ü Steps 4 - Add the routerLink in the appComponent.html
<a routerLink='web-link'> Show Web Link</a>
ü Steps 5 - Add the <router-outlet></router-outlet> in the appComponent.html
<router-outlet></router-outlet>
ü Show the results
Example for Create Routing -
user.component.html -
<h2>Web Links -</h2>
<div>
<ul *ngFor = "let weblink of webliks">
<li>{{weblink}}</li>
</ul>
</div>
user.component.ts-
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {
//constructor() { }
//isAcive =true;
//User List Array
users =['ANil Singh', 'Alok SIngh', 'Raju', 'Sunny','Mark' ,'Indian'];
//This is the web link Array;
webliks =['https://code-sample.com', 'https://code-sample.xyz', 'http://code-view.com'];
ngOnInit() {
}
}
app.module.ts –
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {RouterModule} from '@angular/router'; //Added RouterModule
import { AppComponent } from './app.component';
import { UserComponent } from './user/user.component';
import { Component } from '@angular/core/src/metadata/directives';
@NgModule({
declarations: [
AppComponent,
UserComponent
],
imports: [
BrowserModule,
RouterModule.forRoot([{ //Added Router Module root path and component
path:'web-link',
component: UserComponent
}
])
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.html -
<!--The content below is only a placeholder and can be replaced.-->
<div style="text-align:left">
<h1>
Welcome to {{ title }}!
</h1>
<img width="120" alt="Angular Logo" src="data:image/svg+xml;base64,dfd==">
</div>
<a routerLink='web-link'> Show Web Link</a>
<!-- User List -->
<app-user></app-user>
<!-- router-outlet -->
<router-outlet></router-outlet>
Result looks like –
Before click on anchor link, the application URL (http://localhost:4200) looks like –
After clicked on anchor link, the application URL (http://localhost:4200/web-link) looks like –
I hope you are enjoying with this post! Please share with you friends. Thank you!!