
我们用 NgModules 把 Angular 应用组织成了一些功能相关的代码块。
Angular 本身是被拆成一些独立的 Angular 模块,这样我们在应用中只需要导入需要的 Angular 部分。
每个 Angular 应用至少需要一个root module(根模块) ,实例中为 AppModule 。
接下来我们在 angular-quickstart 目录下创建 app 目录:
$ mkdir app
$ cd app然后在 app 目录下创建 app.module.ts 文件,代码如下所示
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
@NgModule({
imports: [ BrowserModule ]
})
export class AppModule { }由于 QuickStart 是一个运行在浏览器中的 Web 应用,所以根模块需要从 @angular/platform-browser 中导入 BrowserModule 并添加到 imports 数组中。
每个 Angular 应用都至少有一个根组件, 实例中为 AppComponent,app.component.ts 文件代码如下:
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: '<h1>我的第一个 Angular 应用</h1>'
})
export class AppComponent { }代码解析:
接下来我们重新打开 app.module.ts 文件,导入新的 AppComponent ,并把它添加到 NgModule 装饰器的 declarations 和 bootstrap 字段中:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
@NgModule({
imports: [ BrowserModule ],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }接下来我们需要告诉 Angular 如何启动应用。
在 angular-quickstart/app 目录下创建 main.ts 文件,代码如下所示:
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app.module'; const platform = platformBrowserDynamic(); platform.bootstrapModule(AppModule);
以上代码初始化了平台,让你的代码可以运行,然后在该平台上启动你的 AppModule。
在 angular-quickstart 目录下创建 index.html 文件,代码如下所示:
<html> <head> <title>Angular 2 实例 - 菜鸟教程(runoob.com)</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="styles.css"> <!-- 1. 载入库 --> <!-- IE 需要 polyfill --> <script src="node_modules/core-js/client/shim.min.js"></script> <script src="node_modules/zone.js/dist/zone.js"></script> <script src="node_modules/reflect-metadata/Reflect.js"></script> <script src="node_modules/systemjs/dist/system.src.js"></script> <!-- 2. 配置 SystemJS --> <script src="systemjs.config.js"></script> <script> System.import('app').catch(function(err){ console.error(err); }); </script> </head> <!-- 3. 显示应用 --> <body> <my-app>Loading...</my-app> </body> </html>这里值得注意的地方有:
我们可以在 angular-quickstart 目录的 styles.css 文件中设置我们需要的样式:
/* Master Styles */ h1 { color: #369; font-family: Arial, Helvetica, sans-serif; font-size: 250%; } h2, h3 { color: #444; font-family: Arial, Helvetica, sans-serif; font-weight: lighter; } body { margin: 2em; }
打开终端窗口,输入以下命令:
npm start原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。