angular 入门1

1. 配置环境

1.1 安装命令行

cnpm install -g @angular/cli

2. 创建项目

2.1. 创建项目并自动install

ng new heloworld

2.2 创建项目手动install

ng new helloworld --skip-install
然后使用 cnpm install 或者yarn install加速

3. 运行项目

ng serve --open

4. 项目结构

  • e2e: end-to-end测试
  • src: 项目源码
  • .angular-cli.json: angular cli配置文件
  • tsconfig.json
  • tsconfig.app.json
  • tsconfig.spec.json
  • package.json 项目信息、依赖

4.1 源码结构

  • app: 组件、服务
  • assets: 静态资源
  • environments: 多环境文件
  • browserslist: 浏览器支持配置
  • main.ts: 应用入口
  • polyfills.ts: 腻子脚本,能把浏览器对 Web不同点进行标准化
  • styles.css: 全局样式
  • test.ts: 测试入口

4.1.1 app

  • app.module.ts: 根模块
// 浏览器解析模块
import { BrowserModule } from '@angular/platform-browser';
// 模块装饰器
import { NgModule } from '@angular/core';
// app组件
import { AppComponent } from './app.component';
// 告诉angular如何编译启动模块
@NgModule({
  // 当前项目运行的组件
  declarations: [
    AppComponent
  ],
  // 项目运行依赖的其他模块
  imports: [
    BrowserModule
  ],
  // 当前项目所需服务
  providers: [],
  // 指定应用主视图组件
  bootstrap: [AppComponent]
})
// 根模块不导出任何东西,因为其他组件不需要导入根模块
export class AppModule { }

  • app.component.ts 组件
// 组件装饰器
import { Component } from '@angular/core';

@Component({
  // 组件名称
  selector: 'app-root',
  // 模板文件
  templateUrl: './app.component.html',
  // 央视文件
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  // 属性
  title = 'helloworld';
  // 构造函数
  constructor() {
  }
}

  • app.component.html 组件模板
  • app.component.css 组件样式
  • app.component.spec.ts 组件单元测试脚本

5. 自定义组件

5.1 创建组件

ng g component components/header

5.2 使用组件

  • 修改app.component.html
<app-header></app-header>

5.3 定义字段

  • header.component.ts
export class HeaderComponent implements OnInit {
  title = 'this is title'
  constructor() { }

  ngOnInit(): void {
  }

}

5.4 绑定数据

  • header.component.html
<h2>{{title}}</h2>
原创文章 68 获赞 61 访问量 2926

猜你喜欢

转载自blog.csdn.net/zhoudingding/article/details/105718801
今日推荐