I want to navigate from one angular component to another on button click. I have two components app and login.On clicking a button in app.component.html I want to navigate to login.component.html. This is what I tried. Though the URL is getting changed, I am not able to see the html content of the page.
app.component.html
<div class="row">
<div class="col-xs-9"></div>
<div class="col-xs-3">
<input type="button" class="btn btn-primary pull-right" (click)="onSubmit()" value="Next">
</div>
</div>
app.routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { LogInComponent } from './components/log-in/log-in.component';
const routes: Routes = [{ path: 'login', component: LogInComponent }];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
app.component.ts
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
constructor(private router: Router, ) {}
onSubmit() {
this.router.navigate(['/login'])
}
ngOnInit() {}
}
log-in.component.html
<p>it works</p>
On button click the URL changes to /login. However I still see the button UI and not it works. Any help will be appreciated.!Thanks in advance.
I think this would work.
Here is your solution:
onSubmit() {
this.router.navigateByUrl('/login');
}
Another way is:
<button class="nav-item" [routerLink]="['/login']"> Login </button>
Add in your component:
<router-outlet></router-outlet>
There are a few things I miss about your code. For one, app.routing.module
needs to be imported and registered in app.module.ts:
import { AppRoutingModule } from './app-routing.module';
imports: [
BrowserModule,
AppRoutingModule,
...
]
On the other hand, I do not see a router-outlet:
<router-outlet></router-outlet>
I would suggest you to use the app component (app.componet.html) maybe like this:
<app-navbar></app-navbar> // if you use one
<router-outlet></router-outlet> // this is where the routing happens
In the index.html
you reference the app.component just like that:
<body>
<app-root></app-root>
</body>
Then both options suggested by Kishan Patel should work.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.