【问题标题】:angular custom component and angular routing not working角度自定义组件和角度路由不起作用
【发布时间】:2019-11-02 07:11:35
【问题描述】:

文件层次结构:

我可以访问 /test 但它返回空白页。

test.component.html

<h1>Hello its working now </h1>
<p>test works!</p>

test.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.scss']
})
export class TestComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

app-routing.module.ts


import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { TestComponent } from './test/test.component'; 

const routes: Routes = [
  { 
   path: 'test', 
   component: TestComponent 
  },


]; 

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
export const routingComponents =[HomeComponent, TestComponent]



我是角度初学者

【问题讨论】:

  • 你在 app.component.html 文件中添加了router-outlet 吗?

标签: angular routing angular8


【解决方案1】:

在您的 app-routing.module.ts 中,一切似乎都正常。现在,您必须将该模块导入您的 app.module.ts

app-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { TestComponent } from './test/test.component';

const routes: Routes = [
  { path: 'test', component: TestComponent },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

所以在 app.module.ts 中你需要导入 AppRoutingModule。在 imports: [] 数组中只需添加 AppRoutingModule

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';

import { AppComponent } from './app.component';
import { TestComponent } from './test/test.component';

@NgModule({
  imports:      [ BrowserModule, FormsModule, AppRoutingModule ],
  declarations: [ AppComponent, TestComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

现在您可以使用&lt;router-outlet&gt;。因此,当用户导航到下面的“/test”时,将呈现您的 TestComponent。

注意:如果您使用的是 grid-layout,将占用 1 列/行。它将与您的 TestComponent 一起呈现。

app.component.html

<h1> Working example </h1>
<a [routerLink]="['/test']" routerLinkActive="active"> Test </a>
<router-outlet></router-outlet>

【讨论】:

  • 工作示例link
  • 好吧,我错过了 app.component.html 中的 这就是为什么我的字体会出现问题。
  • 是的,并将其包含在 app.component 中:) 如果有帮助,请标记答案。
猜你喜欢
  • 1970-01-01
  • 2017-06-22
  • 1970-01-01
  • 2018-05-17
  • 2017-11-10
  • 2016-03-26
  • 2018-06-07
相关资源
最近更新 更多