1.

How can you use a custom component in multiple pages ?

Answer»

Normally, the simplest way to import a component in a PAGE or another component is by importing it in the module file. But we cannot import a CUSTOM component in two separate modules as it will raise an error alert. So, in order to reuse a custom component like a header or footer component, you can import the custom component in a separate module and then import the module in the target page’s module file. 

Here’s an example. 

Create the component as below ng G component components/site-header. Now create a file custom-components.module.ts in src/app/ 

Add this code - 

import { NgModule } from '@angular/core';  import { SiteHeaderComponent } from './components/site-header/site-header.component';  @NgModule({  declarations: [SiteHeaderComponent],  exports: [SiteHeaderComponent]  }) export CLASS CustomComponentsModule{}  Now import this module in the module file of the page where you want to import  the header component -  import { NgModule } from '@angular/core';  import { CommonModule } from '@angular/common';  import { FormsModule } from '@angular/forms';  import { Routes, RouterModule } from '@angular/router';  import { IonicModule } from '@ionic/angular';  import { CategoryPage } from './category.page';  import { CustomComponentsModule } from './../custom-components.module';  const routes: Routes = [  {  path: '',  component: CategoryPage  }  ]; @NgModule({  imports: [  CommonModule,  FormsModule,  IonicModule,  CustomComponentsModule,  RouterModule.forChild(routes)  ], declarations: [CategoryPage]  }) export class CategoryPageModule {}  LOAD the component by adding it’s selector in the page’s view .  <app-site-header></app-site-header>  <ion-content padding>  <H3> Category Page </H3>  </ion-content>


Discussion

No Comment Found