角度自定义组件和角度布线不起作用

时间:2019-11-02 07:11:35

标签: angular routing angular8

文件层次结构:

enter image description here

我可以访问/ 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]



我是新手。

1 个答案:

答案 0 :(得分:2)

在您的 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 { }

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

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

app.component.html

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