【问题标题】:How to use shared module in all components in angular 4?如何在 Angular 4 的所有组件中使用共享模块?
【发布时间】:2018-09-14 20:55:45
【问题描述】:

我正在使用 Angular 4material。我有两个主要的组成部分......

1) Login and 2) Dashboard

dashboard 中有延迟加载组件,例如 profileemployee 等... 我想设置header,为此我使用了<mat-toolbar>

<mat-toolbar color="primary">
  <mat-toolbar-row>
    <span>My application</span>
    <span class="example-spacer"></span>

    <button mat-button>Logout</button>
  </mat-toolbar-row>  
</mat-toolbar>

组件文件就是这个。

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

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

 constructor() { }

 ngOnInit() {
 }
}

为了在所有dashboard 中使用这个组件,我创建了一个shared module 文件。

src/app/shared/modules/header/header.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HeaderComponent } from 
     '../../../shared/components/header/header.component';
import { MaterialModule } from '../../../material.module';
@NgModule({
imports: [
  CommonModule,
  MaterialModule      
],
declarations: [HeaderComponent],
exports:[HeaderComponent]
})
export class HeaderModule { }

我在模块文件中有import 组件并放入exports 所以,我想我可以使用header 组件。

现在我正在尝试在dashboard 组件中使用它。

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { DashboardComponent } from './dashboard.component';
import { DashboardRoutingModule } from './dashboard-routing.module';
import { MaterialModule } from '../material.module';
import { HeaderModule } from '../shared/modules/header/header.module';

@NgModule({
imports: [
  CommonModule,
  DashboardRoutingModule,
  MaterialModule,
  HeaderModule    
],
declarations: [DashboardComponent]
})
export class DashboardModule { }

我还导入了module 并在entryComponetnt 中设置header componentapp.module.ts 文件中也...

app.module.ts

import { HeaderModule } from './shared/modules/header/header.module';
imports: [
 FormsModule,       
 HeaderModule
],
entryComponents:[HeaderComponent]

问题是当我进入dashboard 页面时,我得到了标题。而且我在console 中也没有收到任何错误。

【问题讨论】:

    标签: module export components angular4-router


    【解决方案1】:

    我只是在仪表板的 html 文件中添加了我的共享组件的 selector 值。

    &lt;app-header&gt;&lt;/app-header&gt;

    它对我有用!

    【讨论】:

      猜你喜欢
      • 2018-12-26
      • 1970-01-01
      • 1970-01-01
      • 2017-10-22
      • 1970-01-01
      • 2017-11-29
      • 1970-01-01
      • 1970-01-01
      • 2018-08-04
      相关资源
      最近更新 更多