[Angular 2] Create Shareable Angular 2 Components

本文介绍了如何在多个Angular2应用程序中复用组件的方法。通过遵循模块模式保持组件与应用逻辑分离,使得组件可以被重复使用。文章详细展示了如何利用CommonModule中的*ngIf等指令,并通过具体代码实例说明了子模块的创建及CommonModule的导入和导出过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值