什么是angular module(ngModule)?
我的理解:其实就是被@NgModule所装饰的普通的类,没有什么特别的。
什么又是@NgModule?
先来看看src/app/app.module.ts里默认代码:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
// @NgModule(元数据)
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { } // 模块名AppModule
declarations数组
这个单词本身的意思是“公告、宣告”,在这里是本模块的依赖项。包括模块可能会依赖的一些组件、指令和管道。引入规则:
- 要使用他们,就必须先引入。
- 一个组件、指令或管道只能被一个模块引入(声明)
- 在declarations中的组件默认只能在当前模块中使用,要想让其他模块使用,必须exports出去
imports数组
providers数组
bootstrap数组
但是通常情况下,里面只会有一个AppComponent。
angular组件又是什么样呢?
先看app组件,src/app/app.component.ts的默认代码:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {// 组件名AppComponent
title = 'hero';
}
可以看出,还是常规操作:引入-->配置-->导出
-
selector:
-
templateUrl:
template 来提供内联模板了(templateUrl和template选项二选一,必填配置)。-
styleUrls:
如果组件比较简单,我们也可以不必单独抽出页面及样式,@Component的配置项可以直接使用内联形式:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<h1>{{title}}</h1>
<h2>My favorite hero is: {{myHero}}</h2>
`,
styles: [`h1 { color: red }`]
})
export class AppComponent { // 组件名AppComponent
title = 'Tour of Heroes';
myHero = 'Windstorm';
}
到此为止,我们其实简单讲了下默认的这个App模块,至于里面的app-routing.module.ts这个文件,咱们后面遇到了再说。
我理解的angular应用总的思路应该是这样的:
举例说明,如果一个angular应用是一个公司,那么AppModule就是这个公司。AppComponent就是这个公司的一个工厂,公司可以有很多个工厂。declearation数组里面的元素就是组成工厂的一部分,比如生产车间、人员管理系统等。imports数组就像是工厂请来的外援,专业性比较强。providers数组就像是后勤部门,提供各种服务。
本文转载自:岩弈,版权归原作者所有,本博客仅以学习目的的传播渠道,不作版权和内容观点阐述,转载时根据场景需要有所改动。



最新评论