Angular学习笔记

配置开发环境

开发工具

搭建NPM私服

推荐使用Nexus,概念和配置方法同Maven私服一致,分为proxy、hosted、group三类。
创建proxy如下:
Angular学习笔记
Remote URL: https://registry.npmjs.org
hosted、group创建方法不再赘述。创建完毕后在home下创建.npmrc文件,其内填写group地址,如下:
registry=http://localhost:8081/repository/npm-public/

NPM

Angular 7,Node.js版本要求8.x或10.x。Angular 8,Node.js版本要求10.9.0或以上。
Windows系统下载安装包安装即可,RHEL、CentOS、Fedora执行如下命令安装:

$ curl --silent --location https://rpm.nodesource.com/setup_8.x | sudo bash -
or
$ curl --silent --location https://rpm.nodesource.com/setup_10.x | sudo bash -
$ sudo yum -y install nodejs

查看nodejs、npm版本:

node -v
npm -v

更新npm:

npm i npm@latest -g

NPM帮助

npm help
npm -l 列出所有命令用法
npm <command> -h 查看某一命令用法,如:
npm ls -h
npm help npm 在浏览器中查看帮助文档,如:
npm help index (Index of all npm documentation)
npm help folders
npm help install

Angular项目创建后,可运行以下命令查看package版本信息:
npm ls 列出所有package
npm view [package] 查看package发布的版本,如:
npm view ng-zorro-antd versions 列出所有ng-zorro-antd版本
npm view ng-zorro-antd 查看最新ng-zorro-antd版本信息
npm view ng-zorro-antd@7.5.0 查看ng-zorro-antd@7.5.0版本信息
进入node_modules/package目录下,运行npm version可查看安装的版本。

Angular CLI

安装Angular CLI

npm install -g @angular/cli@latest

注意:要用@latest
更新Angular CLI
Global package:

npm uninstall -g @angular/cli
npm cache verify
npm install -g @angular/cli@latest

Local project package:

# use rmdir /S/Q node_modules in Windows Command Prompt
# use rm -r -fo node_modules in Windows PowerShell
rm -rf node_modules
npm install --save-dev @angular/cli@latest
npm install

ng帮助

ng help 显示所有命令的帮助
ng [command name] --help  显示某一命令的帮助
ng add <collection> Add support for a library to your project
ng new <name> [options] Creates a new directory and a new Angular app
ng generate <schematic> [options] Generates and/or modifies files based on a schematic
ng update <packages> [options] Updates your application and its dependencies
ng build <project> [options] Builds your app and places it into the output path (dist/ by default)
ng serve <project> [options] Builds and serves your app, rebuilding on file changes
ng test <project> [options] Run unit tests in existing project
ng e2e <project> [options] Run e2e tests in existing project

常用参数:
--aot Build using Ahead of Time compilation
--base-href Base url for the application being built
--i18n-file Localization file to use for i18n
--prod Flag to set configuration to "prod"

Available schematics:

  • serviceWorker
  • application
  • class
  • component
  • directive
  • enum
  • guard
  • interface
  • module
  • pipe
  • service
  • universal
  • appShell
  • library

Angular CLI 6.0的新功能

ng add <collection> Add support for a library to your project
ng update <packages> [options] Updates your application and its dependencies.
ng generate library <name> create a library project within your CLI workspace

更新package

Angular每6个月发布一个主版本,可运行ng update更新package。
ng update
在Project根目录下运行ng update会显示需要更新的package,可以选择更新部分或全部package。

ng update
    We analyzed your package.json, there are some packages to update:

      Name                               Version                  Command to update
     --------------------------------------------------------------------------------
      @angular/cli                       6.2.8 -> 8.0.2           ng update @angular/cli
      @angular/core                      6.1.10 -> 8.0.0          ng update @angular/core
      @angular/core                      6.1.10 -> 7.2.15         ng update @angular/core
      rxjs                               6.3.3 -> 6.5.2           ng update rxjs

    There might be additional packages that are outdated.
    Or run ng update --all to try to update all at the same time.

package.json中的version语法请参见The semantic versioner for npm
npm update

npm update

npm-check-updates
使用npm-check-updates是另一种package更新方式:

  • 安装npm-check-updates
    npm i -g npm-check-updates
  • 升级
    ncu -u
  • 安装新版本
    npm install

UI组件

UI组件,建议从Angular官网推荐的前几个中选择,它们都是开源/免费的:ag-GridAmexioAngular MaterialNG-ZORROAwade Jigsaw

  • ag-Grid(The best Javascript grid in the world)
    数据表格组件,支持排序、筛选、编辑、选择、分组、聚合、旋转等许多强大的功能和操作
  • Amexio
    1. 130+ UI组件
    2. 支持拖拽
    3. 响应式网页设计
    4. 57个主题
    5. 支持图表、地图、仪表盘
  • Angular Material
    Angular官方组件库,提供表单控件、导航、布局、按钮、弹出窗口、数据表格等组件。
  • NG-ZORRO
    阿里出品的企业级UI组件,由阿里计算平台事业部、阿里云等不同部门的一些小伙伴在原业务组件的基础上共同构建而成,设计完全兼容并遵守Ant Design的规范,并定期会与 Ant Design React 版本保持功能同步。NG-ZORRO符合国人使用习惯,国内用户较多。
    ng-zorro-antd 是 Angular 版本 Ant Design 的实现,这意味着只有 Ant Design 支持的交互、功能才会被 ng-zorro-antd 实现。
  • Awade Jigsaw
    中兴大数据UED团队出品

NG-ZORRO

  1. 初始化配置

进入项目文件夹,执行以下命令将自动完成ng-zorro-antd的初始化配置,包括引入国际化文件,导入模块,引入样式文件等

ng add ng-zorro-antd
  1. 定制主题

初始化项目时,运行ng add ng-zorro-antd --theme 会自动配置主题文件src/theme.less,编辑文件即可自定义主题。样式使用了Less作为开发语言。

  1. 代码演示

NG-ZORRO使用简单,文档、示例代码全面,摘录示例代码如下:
表单

import { Component, OnInit } from '@angular/core';
import {
  AbstractControl,
  FormBuilder,
  FormGroup,
  Validators
} from '@angular/forms';

@Component({
  selector: 'nz-demo-form-normal-login',
  template: `
    <form nz-form [formGroup]="validateForm" class="login-form" (ngSubmit)="submitForm()">
      <nz-form-item>
        <nz-form-control>
          <nz-input-group nzPrefixIcon="anticon anticon-user">
            <input type="text" nz-input formControlName="userName" placeholder="Username">
          </nz-input-group>
          <nz-form-explain *ngIf="validateForm.get('userName').dirty && validateForm.get('userName').errors">Please input your username!</nz-form-explain>
        </nz-form-control>
      </nz-form-item>
      <nz-form-item>
        <nz-form-control>
          <nz-input-group nzPrefixIcon="anticon anticon-lock">
            <input type="password" nz-input formControlName="password" placeholder="Password">
          </nz-input-group>
          <nz-form-explain *ngIf="validateForm.get('password').dirty && validateForm.get('password').errors">Please input your Password!</nz-form-explain>
        </nz-form-control>
      </nz-form-item>
      <nz-form-item>
        <nz-form-control>
          <label nz-checkbox formControlName="remember">
            <span>Remember me</span>
          </label>
          <a class="login-form-forgot" class="login-form-forgot">Forgot password</a>
          <button nz-button class="login-form-button" [nzType]="'primary'">Log in</button>
          Or
          <a href="">register now!</a>
        </nz-form-control>
      </nz-form-item>
    </form>
  `,
  styles: [ `
    .login-form {
      max-width: 300px;
    }

    .login-form-forgot {
      float: right;
    }

    .login-form-button {
      width: 100%;
    }
  `
  ]
})
export class NzDemoFormNormalLoginComponent implements OnInit {
  validateForm: FormGroup;

  submitForm(): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[ i ].markAsDirty();
      this.validateForm.controls[ i ].updateValueAndValidity();
    }
  }

  constructor(private fb: FormBuilder) {
  }

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      userName: [ null, [ Validators.required ] ],
      password: [ null, [ Validators.required ] ],
      remember: [ true ]
    });
  }
}

效果图:
Angular学习笔记

  1. NG-ZORRO Table

使用push或splice修改nzData的数据不会生效,需如下操作:

// 增加数据
this.dataSet = [ ...this.dataSet, {
  key    : `${this.i}`,
  name   : `Edward King ${this.i}`,
  age    : '32',
  address: `London, Park Lane no. ${this.i}`
}];
// 删除数据
this.dataSet = this.dataSet.filter(d => d.key !== i);
  1. 测试

使用NG-ZORRO组件的页面,测试时需导入BrowserAnimationsModule和NgZorroAntdModule:

TestBed.configureTestingModule({
     imports: [
       BrowserAnimationsModule,
       NgZorroAntdModule
     ]
})

自定义Pagination

使用NG-ZORRO的Pagination组件,演示如何自定义组件,如何使用HttpParams。

  • 自定义组件PageComponent

page.components.ts

import {Component, EventEmitter, Input, Output} from '@angular/core';
import {DEFAULT_PAGE_SIZE} from '../../vo/page';

@Component({
  selector: 'app-page',
  templateUrl: './page.component.html'
})

export class PageComponent {
  @Input()
  total: number;

  @Input()
  pageIndex: number;

  @Input()
  pageSize = DEFAULT_PAGE_SIZE;

  pageSizeOptions = [10, 20, 30, 40];

  @Output()
  pageChange: EventEmitter<any> = new EventEmitter();

  indexChange(index: any) {
    this.pageChange.emit({'pageIndex': index, 'pageSize': this.pageSize});
  }

  sizeChange(size: any) {
    this.pageChange.emit({'pageIndex': 1, 'pageSize': size});
  }
}

page.components.html

<div style="float: right;">
  <nz-pagination [nzTotal]="total" [(nzPageIndex)]="pageIndex" (nzPageIndexChange)="indexChange($event)" [(nzPageSize)]="pageSize" [nzPageSizeOptions]="pageSizeOptions"
                 (nzPageSizeChange)="sizeChange($event)" nzShowSizeChanger>
  </nz-pagination>
</div>
  • 页面调用
<app-page [total]="total" [pageIndex]="pageIndex" (pageChange)="pageChanged($event)"></app-page>
...
pageChanged(event: any): void {
  this.getAirlines(event.pageIndex - 1, event.pageSize);
}

getAirlines(page: number, size: number): void {
  this.airlineService.searchAirlines(this.airline, page, size)
    .subscribe(data => {
      this.airlines = data.content;
      this.totalItems = data.totalElements;
    });
}
...
  • HttpParams

其余方法略过,最终要调用HttpClient的get方法,需要封装查询参数、分页参数(后台使用Spring Data分页方法):

...
this.http.get<T>('url', {params})
...

封装方法如下:

import {HttpParams} from '@angular/common/http';
import {DEFAULT_PAGE_SIZE} from '../vo/page';

...
  pageParams<T>(data: T, page?: number, size?: number): HttpParams {
    let params = new HttpParams()
      .set('page', page ? page.toString() : '0')
      .set('size', size ? size.toString() : DEFAULT_PAGE_SIZE.toString());

    Object.keys(data).forEach(function (key) {
      let value = data[key];
      if (value === '') {
        return;
      }
      if (value ×××tanceof Date) {
        value = value.toISOString();
      }
      params = params.set(key, value);
    });
    return params;
  }

注意,不能写成这样:

let params = new HttpParams();
params.set('orderBy', '"$key"')
params.set('limitToFirst', "1");

HttpParams是不可变的,上面写法将返回空值。

ExcelJS

ExcelJS是读写XLSX和CSV格式文件的开源组件,MIT License。相对于SheetJS组件,ExcelJS更容易设置Excel样式。
安装ExcelJS:

npm install --save exceljs

ExcelJS写文件需使用FileSaver.js

npm install --save file-saver

然后在tsconfig.json中添加:

"paths": {
  "exceljs": [
    "node_modules/exceljs/dist/exceljs.js",
    "node_modules/file-saver/dist/FileSaver.js"
  ]
}

使用示例:

import {Workbook} from 'exceljs';
import * as fs from 'file-saver';

...
  const workBook = new Workbook();
  const workSheet = workBook.addWorksheet('Sheet1');
  workSheet.columns = [
    {header: 'ID', key: 'id', width: 12},
    {header: 'Name', key: 'name', width: 12},
    {header: 'Email', key: 'email', width: 50}
  ];

    var rows = [
    {id:1, name: 'Jason', email: 'jason@163.com'},
        {id:2, name: 'Coco', email: 'coco@163.com'}
    ];
    worksheet.addRows(rows);

  workSheet.getRow(1).eachCell((cell, colNumber) => {
    cell.fill = {type: 'pattern', pattern: 'solid', fgColor: {argb: 'FF00CCFF'}, bgColor: {argb: 'FFFFFF00'}};
    cell.font = {bold: true};
  });
  workSheet.getColumn('email').alignment = { vertical: 'bottom', horizontal: 'left' };

  workBook.xlsx.writeBuffer().then(value => {
    const blob = new Blob([value], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
    fs.saveAs(blob, 'test');
  });
...

CKEditor 4

开源WYSIWYG HTML编辑器,支持GPL, LGPL, MPL协议。用法如下:

  1. Include CKEditor javascript files in your application
<script src="https://cdn.ckeditor.com/4.7.3/full-all/ckeditor.js"></script>
  1. Install ng2-ckeditor
npm install --save ng2-ckeditor

3.Include CKEditorModule in your main module

import { CKEditorModule } from 'ng2-ckeditor';

@NgModule({
  // ...
  imports:      [
    CKEditorModule
  ],
  // ...
})
export class AppModule { }
  1. usage
<ckeditor [(ngModel)]="content" [config]="{extraPlug×××: 'divarea'}" name="editor"></ckeditor>

学习资料

Angular
Angular中文
TypeScript
TypeScript中文网
NPM Docs
RxJS
Learn Angular 5
Angular 4.x 修仙之路
NG-ZORRO
CKEditor Ecosystem
Angular HTTP Client - Quickstart Guide
Angular Architecture - Smart Components vs Presentational Components

转载于:https://blog.51cto.com/7308310/2072564

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值