目录
指令
在 Angular 中最常用的指令分为两种,它们分别是 属性型指令 和 结构型指令。
NgClass
- 作用:添加或移除一组 CSS 类
NgStyle
- 作用:添加或移除一组 CSS 样式
NgModel
- 作用:双向绑定到 HTML 表单元素
NgIf
- 作用:根据条件添加或移除 DOM
- 语法:
<div class="box" *ngIf="false">看不见我</div>
<!-- isSpecial is true -->
<div [class.hidden]="!isSpecial">Show with class</div>
<div [class.hidden]="isSpecial">Hide with class</div>
<div [style.display]="isSpecial ? 'block' : 'none'">Show with style</div>
<div [style.display]="isSpecial ? 'none' : 'block'">Hide with style</div>
NgSwitch
- 作用:类似于 JavaScript 中的 switch 语句,根据条件渲染多个选项中的一个。
- 语法:该指令包括三个相互协作的指令:
NgSwitch
、NgSwitchCase
、NgSwitchDefault
<div [ngSwitch]="currentHero.emotion">
<app-happy-hero *ngSwitchCase="'happy'" [hero]="currentHero"></app-happy-hero>
<app-sad-hero *ngSwitchCase="'sad'" [hero]="currentHero"></app-sad-hero>
<app-confused-hero *ngSwitchCase="'confused'" [hero]="currentHero"></app-confused-hero>
<app-unknown-hero *ngSwitchDefault [hero]="currentHero"></app-unknown-hero>
</div>
NgFor
- 作用:列表渲染
- 语法:
<div *ngFor="let hero of heroes">{{hero.name}}</div>
带索引的 *ngFor
<ul>
<li *ngFor="let item of todos; let i = index">{{ item.title + i }}</li>
</ul>
自定义指令
参考文档:
表单处理
和服务端交互
启用 Http 服务
- open the root
AppModule
, - import the
HttpClientModule
symbol from@angular/common/http
, - add it to the
@NgModule.imports
array.
// app.module.ts:
import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
// Import HttpClientModule from @angular/common/http
import {HttpClientModule} from '@angular/common/http';
@NgModule({
imports: [
BrowserModule,
// Include it under 'imports' in your application module
// after BrowserModule.
HttpClientModule,
],
})
export class MyAppModule {}
发起一个 get 请求
@Component(...)
export class MyComponent implements OnInit {
results: string[];
// Inject HttpClient into your component or service.
constructor(private http: HttpClient) {}
ngOnInit(): void {
// Make the HTTP request:
this.http.get('/api/items').subscribe(data => {
// Read the result field from the JSON response.
this.results = data['results'];
});
}
}
Reading the full response
this.http
.get('https://jsonplaceholder.typicode.com/posts/1', {observe: 'response'})
.subscribe(res => {
console.log(res)
})
结果示例:
错误处理
http
.get('/api/items')
.subscribe(
// Successful responses call the first callback.
data => {...},
// Errors will call this callback instead:
err => {
console.log('Something went wrong!');
}
);
路由处理
基本用法
- 添加
AppRoutingModule
ng generate module app-routing --flat --module=app
app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { FooComponent } from './foo/foo.component'
import { BarComponent } from './bar/bar.component'
const routes: Routes = [
{
path: 'foo',
component: FooComponent
},
{
path: 'bar',
component: BarComponent
}
]
@NgModule({
imports: [
RouterModule.forRoot(routes)
],
exports: [ RouterModule ]
})
export class AppRoutingModule {}
设置路由出口:
<h1>{{title}}</h1>
<router-outlet></router-outlet>
设置导航链接:
<ul>
<li>
<a routerLink="/foo">Go Foo</a>
</li>
<li>
<a routerLink="/bar">Go Foo</a>
</li>
</ul>
导航链接 routerLink
路由对象
- path
- 不能以
/
开头
- 不能以
- component
默认路由:
{ path: '', redirectTo: '/dashboard', pathMatch: 'full' },
动态路由匹配
动态路径配置:
{ path: 'detail/:id', component: HeroDetailComponent },
导航链接:
<a *ngFor="let hero of heroes" class="col-1-4"
routerLink="/detail/{{hero.id}}">
在组件中解析获取动态路径参数:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Location } from '@angular/common';
@Component({
selector: 'app-user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {
constructor(
private route: ActivatedRoute,
private location: Location
) { }
ngOnInit() {
const id = this.route.snapshot.paramMap.get('id')
console.log(id)
}
}
路由导航
后退:
this.location.back();
Angular CLI
安装
依赖
- Node 6.9.0 or higher
- NPM 3 or higher
- Python
- C++ 编译工具
安装
npm install -g @angular/cli
使用帮助
ng help
初始化项目
ng new <项目名称>
启动开发服务
ng serve
ng serve
默认占用 4200
端口号,可以通过下面选项配置:
ng serve --port 4201
创建组件,指令,过滤器和服务
# 创建组件
ng generate component my-new-component
# 创建组件别名
ng g component my-new-component # using the alias
# components support relative path generation
# if in the directory src/app/feature/ and you run
ng g component new-cmp
# your component will be generated in src/app/feature/new-cmp
# but if you were to run
ng g component ../newer-cmp
# your component will be generated in src/app/newer-cmp
# if in the directory src/app you can also run
ng g component feature/new-cmp
# and your component will be generated in src/app/feature/new-cmp
可辅助创建资源的功能列表:
Scaffold | Usage |
---|---|
Component | ng g component my-new-component |
Directive | ng g directive my-new-directive |
Pipe | ng g pipe my-new-pipe |
Service | ng g service my-new-service |
Class | ng g class my-new-class |
Guard | ng g guard my-new-guard |
Interface | ng g interface my-new-interface |
Enum | ng g enum my-new-enum |
Module | ng g module my-module |
angular-cli will add reference to components
, directives
and pipes
automatically in the app.module.ts
. If you need to add this references to another custom module, follow this steps:
ng g module new-module
to create a new module- call
ng g component new-module/new-component
This should add the new component
, directive
or pipe
reference to the new-module
you've created.
在脚手架项目中使用 SASS 预处理器
SASS 是一款非常好用的 CSS 预编译器,Bootstrap 官方从4.0开始已经切换到了 SASS。
如果想要在脚手架项目中使用 SASS 预处理器,我们需要自己手动修改一些配置文件,请按照以下步骤依次修改:
- angular-cli.json 里面的 styles.css 后缀改成
.scss
当你后面再使用 ng g c ***
自动创建组件的时候,默认就会生成 .scss
后缀的样式文件了。
- angular-cli.json 里面的 styleExt 改成 .scss
- src 下面 styles.css 改成 styles.scss
- app.component.scss
- app.component.ts 里面对应修改
改完之后,重新 ng serve
,打开浏览器查看效果。
SASS 的 API 请参考官方网站 。
SASS 只是一个预编译器,它支持所有 CSS 原生语法。利用 SASS 可以提升你的 CSS 编码效率,增强 CSS 代码的可维护性,但是千万不要幻想从此就可以不用学习 CSS 基础知识了。
更新 Angular CLI
其它
切换包管理器
# 默认为 npm
ng set --global packageManager=npm
# 将包管理器设置为 yarn
ng set --global packageManager=yarn
# 将包管理器设置为 cnpm
ng set --global packageManager=cnpm
详细参考文档