i am new to angular. Creating simple navigation from one component to other. Using router.navigate method for navigation.
When a button is clicked url is getting changed but that particular component html page is not getting shown up.
this.router.navigate(['login']);
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { LoginComponent } from './Components/ProfileComponents/login/login.component';
import { Routes, RouterModule } from '@angular/router';
import { TestrouteComponent } from './testroute/testroute.component';
const appRoutes: Routes = [
{ path: 'login', component: TestrouteComponent }
];
@NgModule({
declarations: [
AppComponent,
LoginComponent,
TestrouteComponent
],
imports: [
BrowserModule,
RouterModule.forRoot(appRoutes, { enableTracing: true })
],
exports: [RouterModule],
providers: [
],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.ts
import { Component } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private router: Router, private _activateRoute: ActivatedRoute) {}
title = 'app';
testRouting() {
this.router.navigate(['login']);
}
}
app.component.html
<div style="text-align:center">
<h1>
Welcome
</h1>
</div>
<h2>Here are some links to help you start: </h2>
<button (click)="testRouting()">test</button>
testroute.component.html
<p>
testroute works!
</p>
testroute.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-testroute',
templateUrl: './testroute.component.html',
styleUrls: ['./testroute.component.css']
})
export class TestrouteComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
plain code just want to check the router.navigate functionality. Not sure exactly what i am missing here.
I think you forgot to add your <router-outlet></router-outlet> inside your app.component.html file.
It will add the component defined in your router module when the url matches a given route. So in your case, it will add the TestrouteComponent.
For instance in your app.component.html
<div style="text-align:center">
<h1>
Welcome
</h1>
</div>
<h2>Here are some links to help you start: </h2>
<button (click)="testRouting()">test</button>
<router-outlet></router-outlet>
Note that your h1, h2, button elements will still be visible even when the route change when the html is set up like this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With