欢迎来到 Angular 中文社区!以下是关于创建您的第一个 Angular 应用的指南。
简介
Angular 是一个用于构建高性能和可扩展的 Web 应用的框架。通过本指南,您将学习如何创建一个简单的 Angular 应用,并了解其基本结构和概念。
安装 Angular CLI
首先,您需要安装 Angular CLI,这是 Angular 的官方命令行界面,用于创建、开发、测试和部署 Angular 应用。
npm install -g @angular/cli
创建新应用
使用 Angular CLI 创建一个新应用:
ng new my-first-angular-app
这将在当前目录下创建一个名为 my-first-angular-app
的新目录。
启动应用
进入新创建的应用目录,并启动开发服务器:
cd my-first-angular-app
ng serve
默认情况下,应用将在 http://localhost:4200/
上运行。
应用结构
一个典型的 Angular 应用具有以下结构:
- src: 应用源代码目录
- app: 应用的主要组件和模块
- components: 组件文件
- services: 服务文件
- models: 模型文件
- pipes: 管道文件
- directives: 指令文件
- assets: 静态文件,如图片、图标等
- environments: 环境配置文件
- index.html: 应用的入口 HTML 文件
- main.ts: 应用的入口 TypeScript 文件
- polyfills.ts: polyfill 文件
- styles.css: 全局样式文件
- app.module.ts: 应用的根模块
- app.component.html: 根组件的模板文件
- app.component.ts: 根组件的逻辑文件
- app.component.css: 根组件的样式文件
- app: 应用的主要组件和模块
创建第一个组件
在 src/app
目录下创建一个新的组件:
ng generate component my-first-component
这将在 src/app/components
目录下创建一个新的 my-first-component
文件夹,其中包含组件的模板、样式和 TypeScript 文件。
添加内容
在 my-first-component
的模板文件 my-first-component.html
中,添加以下内容:
<h1>欢迎来到 Angular!</h1>
<p>这是您的第一个 Angular 组件。</p>
在 my-first-component
的 TypeScript 文件 my-first-component.ts
中,您可以添加组件的逻辑。
测试应用
在浏览器中打开 http://localhost:4200/
,您应该能看到欢迎信息。
更多资源
如果您想了解更多关于 Angular 的信息,请访问我们的官方文档。
Angular Logo