Angular2入门之新建模块与组件

Angular2新建模块和其中的组件的需要注意一些问题。
  本文新建一个LayoutModule模块,目录如下图:


Angular2入门之新建模块与组件_第1张图片
新建layout模块的文件目录.png

1. 首先,创建文件夹如图中所示

+layout
+++main-layout
+++navigation

2. 在layout文件夹下创建LayoutModule

import { NgModule } from '@angular/core';
import { MainLayoutComponent } from './main-layout/main-layout.component';
import { NavigationComponent } from './navigation/navigation.componennt';

@NgModule({
    imports: [],
    declarations: [
        MainLayoutComponent,
        NavigationComponent
    ],
    exports: []
})
export class LayoutModule { }

需要使用import将模块包含的组件都引入进来,然后在declarations中声明。

3.创建本模块中的组件以及相应的模板

  • MainLayoutComponent的代码如下:
import { Component } from '@angular/core';

@Component({
    selector: 'app-main-layout',
    templateUrl: './main-layout.component.html',
    styleUrls: []
})
export class MainLayoutComponent {}
  • main-layout.component.html代码很简单:
    //组件使用同模块中的组件不需要import
  • NavigationComponent代码如下:
    import { Component } from '@angular/core';
    
    @Component({
        selector: 'sa-navigation',
        templateUrl: 'navigation.component.html',
        styleUrls: []
    })
    
    

export class NavigationComponent {}
```

  • navigation.component.html中,我们只写一句话
    Hello, world!

4.将模块引入AppModule

app.module.ts中代码如下:

//app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { LayoutModule } from './layout/layout.module'; //这里需要import

@NgModule({
declarations: [
 AppComponent
],
imports: [
 BrowserModule,
 FormsModule,
 HttpModule,
 LayoutModule,       //这里需要imports
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
 ```
可以看出,分别在顶部的``import``和``@NgModule``中的``imports``数组中添加新加入的模块。

##5.使用模块中的组件
  使用模块中的组件,我们可以这样使用,在``app.component.html``中通过添加标签使用 ````
  我们虽然在AppModule中,引入了LayoutModule,但是你查看``layout.module.ts``文件,会发现``exports``数组是空的,也就是LayoutModule没有把这个组件暴露出来,这样AppModule中的组件不能找到````所代表的组件的。
  所以一个模块中的组件想要被其他模块使用,需要在``exports``数组中暴露出去。在``layout.module.ts``中添加``exports``数组。

//layout.module.ts
@NgModule({
imports: [],
declarations: [
MainLayoutComponent,
NavigationComponent
],
exports: [
MainLayoutComponent //新添加的代码
]
})

**注意:**我们在``main-layout.component.html``中使用了````,而没有导入,因为二者是处于同一个模块的,不需要额外导入。

##6.运行结果
  在项目目录下运行``npm start``,打开浏览器,就可以看到“Hello, world!”
##总结:
1. 模块A想要使用新创建的模块B,需要在A模块中导入B,并添加到A模块的``imports``数组中
2. A模块中的组件想要使用B模块中的组件b1,需要在B模块的``exports``数组中添加组件b1,即将其暴露出来。

你可能感兴趣的:(Angular2入门之新建模块与组件)