这个问题曾经被问过, 但所有答案似乎都没有帮助我。 我无法在angular上路由到其他页面,相反,它只是在主页末尾添加了所需组件的HTML。这是我的代码:
app.module.ts
polyfill.ts
app.component.html
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { ToggleFullscreenDirectiveDirective } from './toggle-fullscreen-directive.directive';
import { HttpClientModule } from '@angular/common/http';
import { AnnouncementsComponent } from './announcements/announcements.component';
import { AdminComponent } from './admin/admin.component';
import { RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { ToggleFullscreenDirectiveDirective } from './toggle-fullscreen-directive.directive';
import { HttpClientModule } from '@angular/common/http';
import { AnnouncementsComponent } from './announcements/announcements.component';
import { AdminComponent } from './admin/admin.component';
import { RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
@NgModule({
declarations: [
AppComponent,
ToggleFullscreenDirectiveDirective,
AnnouncementsComponent,
AdminComponent
],
imports: [
BrowserModule,
HttpClientModule,
RouterModule.forRoot([
{ path: '', component: AppComponent },
{ path: 'admin', component: AdminComponent }
])
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
index.html
...My custom html
<router-outlet></router-outlet>
根据其他答案,问题可能与进口有关, 我试图删除一些我在代码上使用过的代码,例如全屏切换,另一种可能性是可能检查了控制台错误,没有问题。谁能帮我? 我迷路了!
谢谢
答案 0 :(得分:4)
App.component 已呈现,它是所有其他组件的容器。所以不要在路由中包含它,
因此,您要做的是从App.component复制代码并将该代码添加到新组件(称为 home.component )
然后按如下所示配置路由。
RouterModule.forRoot([
{ path: '', component: HomeComponent},
{ path: 'admin', component: AdminComponent }
])
app.component.html
<router-outlet></router-outlet>
home.component.html
...My custom html
答案 1 :(得分:3)
根据您的路线,尝试将routerModule更改为:
RouterModule.forRoot([
{ path: '', redirectTo: '/admin', pathMatch: 'full' },
{ path: 'admin', component: AdminComponent }
])
顺便说一句,当您创建forRoot路由器时,Angular会从应用程序(通常是app.component.html)的引导程序组件中寻找<router-outlet>
选择器。无需使用forRoot配置指定您的app.component!