初学者:想在Angularjs 4中从一页导航到另一页

时间:2018-08-16 05:54:12

标签: angular web-applications angular-routing

请帮助我了解如何将页面以一定角度导航到另一页面。这是我所做的。

  1. 我创建一个项目(ng create)
  2. 添加了两个组件(“主页”和“关于”)
  3. 添加一个app-routing.module.ts文件和我写此代码的int文件

    import { NgModule }      from '@angular/core';
    import { RouterModule, Routes } from '@angular/router';
    import { HomeComponent }  from './home/home.component';
    import { AboutUsComponent } from './about-us/about-us.component';
    
    const routes: Routes = [
            { path: 'home', component: HomeComponent },
            {path:'about', component: AboutUsComponent}
    ];
    @NgModule({
      imports: [ RouterModule.forRoot(routes) ],
      exports: [ RouterModule ]
    })
    export class AppRoutingModule{ }
    
  4. 在app.module.ts中

    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    import { FormsModule }   from '@angular/forms';
    
    import { AppComponent } from './app.component';
    import { HomeComponent } from './home/home.component';
    import { AboutUsComponent } from './about-us/about-us.component';
    import { AppRoutingModule } from './app-routing.module';
    
    @NgModule({
       declarations: [
         AppComponent,
         HomeComponent,
         AboutUsComponent
      ],
    imports: [
       BrowserModule,
       FormsModule,
       AppRoutingModule
    ],
     providers: [],
     bootstrap: [AppComponent]
    })
    export class AppModule { }
    

当我输入http://localhost:4200/homehttp://localhost:4200/about时,它没有导航。

谢谢

3 个答案:

答案 0 :(得分:3)

您需要在<router-outlet></router-outlet>标记文件中添加AppComponent。这样一来,您就可以在HomeComponent视图中加载AboutUsComponentAppComponent并进行导航。

app.component.html

<h1> App Component </h1>
<router-outlet></router-outlet>

答案 1 :(得分:1)

还使用<router-outlet>redirectTo

  

app.component.html

<h1> App Component </h1>
<router-outlet></router-outlet>
  

app-routing.module.ts

const routes: Routes = [
        { path: '', redirectTo: 'home', pathMatch: 'full' },
        { path: 'home', component: HomeComponent },
        {path:'about', component: AboutUsComponent}
];

答案 2 :(得分:0)

导航到html

<a [routerLink]="['/user/bob']" >
  link to user component
</a>

该组件将加载到默认插座中,您也可以创建自定义插座