Angular学习笔记
配置开发环境
开发工具
VS Code / IntelliJ IDEA / WebStorm
搭建NPM私服
推荐使用Nexus,概念和配置方法同Maven私服一致,分为proxy、hosted、group三类。
创建proxy如下:
Remote URL: https://registry.npmjs.org
然后创建hosted、group,不再赘述。
最后在home下创建.npmrc文件,其内填写public地址,如下:
registry=http://localhost:8081/repository/npm-public/
NPM
Angular 6开发,Node.js版本要求8.x或以上,npm版本要求5.x或以上。运行node -v、npm -v查看版本。
在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
安装Node.js后,更新npm:
npm i npm@latest -g
NPM帮助
npm helpnpm -l 列出所有命令用法npm <command> -h 查看某一命令用法,如:npm ls -hnpm help npm 在浏览器中查看帮助文档,如:npm help index (Index of all npm documentation)npm help foldersnpm help install
运行npm ls 可查看版本是否匹配。
运行npm view [package] 可查看某一package发布的版本,如:
npm view ngx-bootstrap [versions]
进入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 clean # if npm version is > 5 then use `npm cache verify` to avoid errors (or to avoid using --force)npm install -g @angular/cli@latest
Local project package:
# use rmdir /S/Q node_modules dist in Windows Command Prompt# use rm -r -fo node_modules,dist in Windows PowerShellrm -rf node_modules distnpm install --save-dev @angular/cli@latestnpm install
ng帮助
ng help 显示所有命令的帮助 ng [command name] --help 显示某一命令的帮助ng add <collection> Add support for a library to your projectng 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、ng update、ng generate 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
在Project根目录下运行ng update后会显示需要更新的package,可以选择更新某一package或全部package。
package.json中的version语法请参见The semantic versioner for npm
npm-check-updates
使用npm-check-updates是另一种更新package的方式:
安装npm-check-updates
npm i -g npm-check-updates升级
ncu -u安装新版本
npm install
UI组件
UI组件,建议从Angular官网推荐的前四个中选择,它们都是开源/免费的:ag-Grid、Amexio、Angular Material、NG-ZORRO。
ag-Grid(The best Javascript grid in the world)
数据表格组件,支持排序、筛选、编辑、选择、分组、聚合、旋转等许多强大的功能和操作Amexio
130+ UI组件
支持拖拽
响应式网页设计
57个主题
支持图表、地图、仪表盘
Angular Material
Angular官方组件库,提供表单控件、导航、布局、按钮、弹出窗口、数据表格等组件。
NG-ZORRO
阿里出品的企业级UI组件,由阿里计算平台事业部、阿里云等不同部门的一些小伙伴在原业务组件的基础上共同构建而成,设计完全兼容并遵守Ant Design的规范,并定期会与 Ant Design React 版本保持功能同步。NG-ZORRO符合国人使用习惯,国内用户较多。
ng-zorro-antd 是 Angular 版本 Ant Design 的实现,这意味着只有 Ant Design 支持的交互、功能才会被 ng-zorro-antd 实现。
NG-ZORRO
初始化配置
进入项目文件夹,执行以下命令将自动完成 ng-zorro-antd 的初始化配置,包括引入国际化文件,导入模块,引入样式文件等
ng add ng-zorro-antd
定制主题
初始化项目时,运行ng add ng-zorro-antd --theme 会自动配置主题文件src/theme.less,修改文件内容即可自定义主题。样式使用了Less作为开发语言,版本为2.7。
代码演示
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 ] }); } }
效果图:
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);
测试
使用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 instanceof Date) { value = value.toISOString(); } params = params.set(key, value); }); return params; }
注意,不能写成这样:
let params = new HttpParams();params.set('orderBy', '"$key"')params.set('limitToFirst', "1");
HttpParams是不可变的,上面写法将返回空值。
CKEditor 4
开源WYSIWYG HTML编辑器,支持GPL, LGPL, MPL协议。用法如下:
Include CKEditor javascript files in your application
<script src="https://cdn.ckeditor.com/4.7.3/full-all/ckeditor.js"></script>
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 { }
usage
<ckeditor [(ngModel)]="content" [config]="{extraPlugins: '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
---------------------------------
本文转自Jason_川川博客51CTO博客
如需转载,请联系作者授权
原文链接:http://blog.51cto.com/7308310/2072564
- 点赞
- 收藏
- 关注作者
评论(0)