Search code examples
moduleexportcomponentsangular4-router

How to use shared module in all components in angular 4?


I'm using Angular 4 with material. And I have main two components...

1) Login and 2) Dashboard

There are lazy loading components in dashboard like profile , employee etc... I want to set header and for that I have used <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>

and component file is this .

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() {
 }
}

To use this component in all dashboard I have create one shared module file.

In 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 { }

I have import component in module file and put in exports so, I think I'm able to use header component.

Now I'm trying to use it in dashboard component.

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 { }

I have also import module and set header component in entryComponetnt in app.module.ts file also...

app.module.ts

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

The issue is I'm getting header when I go dashboard page. And also I'm not getting any error in console.


Solution

  • I just add my shared component's selector value in dashboard's html file.

    <app-header></app-header>

    It works for me!