本文由Scarb发表于金甲虫的博客,转载请注明出处
Angular 笔记
Flex 布局

*ngFor

1 2 3 4 5
| <ul> <li *ngFor="let item of topMenus; let i = index"> <a href="{{item.link}}">{{item.title}}</a> </li> </ul>
|
1 2 3 4 5
| <ul> <li *ngFor="let item of topMenus; let first = first; let last = last"> <a href="{{item.link}}">{{item.title}}</a> </li> </ul>
|
1 2 3 4 5
| <ul> <li *ngFor="let item of topMenus; let odd = odd; let even = even"> <a href="{{item.link}}">{{item.title}}</a> </li> </ul>
|
1 2 3 4 5
| <ul> <li *ngFor="let item of topMenus; trackBy: trackElement"> <a href="{{item.link}}">{{item.title}}</a> </li> </ul>
|
样式绑定的几种方式
- 执行
class
属性,用于单个样式的条件绑定最为合适
1
| <div [class.className]="条件表达式">...</div>
|
- 添加
class
属性,true
则添加,false
则不添加
1
| <div [ngClass]="{'one': true, 'two': true, 'three': false}">...</div>
|
1
| <div [ngStyle]="{'color': someColor, 'font-size': fontSize}">...</div>
|
组件生命周期

在组件类中引用模板资源

双向绑定 ngModel
- FormsModule中提供的指令
- 使用
[ngModel] = "变量"
形式进行双向绑定
- 其实是一个语法糖
1
| <input [ngModel]="username" (ngModelChange)="username = $event"></input>
|
共享模块
将某个模块中,其他多个模块需要用到的组件、指令和管道导入到共享模块中。
其他每个模块都导入共享模块
指令的样式和事件绑定
指令没有模板,要寄宿在一个元素之上 - 宿主(Host)
@HostBinding
绑定宿主的属性或者样式
@HostListener
绑定宿主的事件
组件的样式中也可使用:host
这样的一个伪类选择器
投影组件
ng-content
:组件的动态内容
select
属性可以选择可用的样式类/HTML标签/指令
1
| <ng-content select="样式类/HTML标签/指令"></ng-content>
|
路由
路由定义

1 2 3 4 5 6 7 8 9 10 11
| const routes: Routes = [ {path: '', component: HomeComponent}, {path: 'path', component: FeatureComponent}, {path: '**', component: PageNotFoundComponent} ];
@NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
|
子路由写法
1 2 3 4 5 6 7 8 9 10 11 12
| const routes: Routes = [ { path: 'home', component: HomeComponent, children: [ { path: ':id', component: ChildComponent } ] } ]
|
管道
依赖注入
声明和使用依赖注入
- 提供服务
@Injectable()
将服务标记为可供注入的服务
- 模块中声明
- 在组件中使用
- 构造函数中直接声明
- Angular框架完成自动注入
代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| @Injectable() class Product { constructor(private name: string, private color: string) { } }
@Injectable() class PurchaseOrder { private amount: number;
constructor(private product: Product) { } }
const injector = Injector.create({ providers: [ { provide: Product, useFactory: () => { return new Product('大米手机', '黑色'); }, deps: [] }, { provide: PurchaseOrder, useClass: PurchaseOrder, deps: [Product] } ] }); console.log(injector.get(Product)); console.log(injector.get(PurchaseOrder)); }
|