Components that you use across multiple applications need to follow a module pattern that keeps them separate from your application logic. This will allow you to make these Angular 2 components reusable and shareable and is the same pattern followed by many libraries that you may import into your projects.
The structure likes this:
In widget-one.component.html. we use *ngIf to control the display, to do this, we have to import CommonModule from angular/common, which inlcudes NgIf, NgFor....
import { NgModule} from '@angular/core'; import { CommonModule } from '@angular/common'; import {WidgetOneComponent} from './widget-one.component'; import {WidgetTwoComponent} from './widget-two.component'; @NgModule({ imports: [CommonModule], declarations: [WidgetOneComponent, WidgetTwoComponent], exports: [WidgetOneComponent, WidgetTwoComponent, CommonModule] }) export class WidgetsModule { }
The CommonModule is available for root Module. When you create a sub module, it won't import CommonModule by default, so you need to imports it and exprots it to other sub module for free.
widget-one.component.ts:
import { Component, OnInit } from '@angular/core'; @Component({ moduleId: module.id, selector: 'widget-one', templateUrl: '<div *ngIf=selected'This is widget one </div> }) export class WidgetOneComponent implements OnInit { selected = false; constructor() { } ngOnInit() { } }