按钮重定向到Angular 5中的另一个页面

时间:2018-03-28 07:22:18

标签: asp.net angular angular5

大家好,首先我是第一次学习角5。我想要的是使用按钮从页面重定向到另一个。我不知道如何使它工作。我正在使用角度5.这是我的代码:

Home.component.html

<div style="text-align:center">
 <button (click)="btnClick()">Add Employee</button>
</div>
<br>
<div style="text-align:center">
 <button (click)="btnClick()">Employee List</button>
</div>
<br>

Home.component.ts

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
@Component({
    selector: 'app-home',
    templateUrl: './home.component.html',
    styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

    constructor(private router: Router) {}

    ngOnInit() {
    }

    btnClick(){
        this.router.navigate(['/employees']);
    }
}

我没有route.config,但我有app.module.ts,如果我做错了请告诉我

app.module.ts:

...........
import { HomeComponent} from './home/home.component';
import { RouterModule, Routes } from '@angular/router';
import { EmployeesComponent } from './employees/employees.component';
  @NgModule({
declarations: [
  AppComponent,
  EmployeesComponent,
  EmployeeComponent,
  EmployeeListComponent,
  AppHeaderComponent,
  AppFooterComponent,
  HomeComponent,

],
imports: [
  BrowserModule,
  FormsModule,
  HttpModule,
  ToastrModule.forRoot(),



],

1 个答案:

答案 0 :(得分:0)

您似乎需要先配置应用程序的路由,以便路由器插座知道在调用['/ employees']时要加载的组件

https://angular.io/tutorial/toh-pt5

下有一个很好的解释

首先,您必须配置路线

import { HomeComponent} from './home/home.component';
import { RouterModule, Routes } from '@angular/router';
import { EmployeesComponent } from './employees/employees.component';
    const routes: Routes = [
  { path: 'home', component: HomeComponent }
  { path: 'employees', component: EmployeesComponent }
  { path: '', redirectTo: 'home', pathMatch: 'full' }
];
  @NgModule({
declarations: [
  AppComponent,
  EmployeesComponent,
  EmployeeComponent,
  EmployeeListComponent,
  AppHeaderComponent,
  AppFooterComponent,
  HomeComponent,

],
imports: [
  BrowserModule,
  FormsModule,
  HttpModule,
  ToastrModule.forRoot()
  RouterModule.forRoot(routes),



],

然后在您的AppComponent HTML中,您需要使用路由器插座(假设您希望您的员工在应用程序组件上显示)

<router-outlet></router-outlet>