3.1 应用
1.利用angular-cli创建一个项目
1.ng new inventory_app #创建一个新的项目
2.ng generate component product #新建一个组件
2.一个组件的构建方法
@Component({
selector: 'single-component',
inputs: ['name', 'age'],
template: `<div></div>`,
})
class SingleComponent {
name: string;
age: number;
constructor() {
}
}
// 使用
<single-component [name]="myName" [age]="myAge"></single-component>
3.5.4 触发自定义事件
@Component({
selector: 'single-component',
outputs: ['putRingOnIt'],
host: {"class": "item"}, // 在宿主元素上添加class为item(3.6.1)
template: `<button (click)="liked()">Like it ?</button>`
})
class SingleComponent {
putRingOnIt: EventEmitter<string>;
constructor() {
this.putRingOnIt = new EventEmitter();
}
liked(): void {
this.putRingOnIt.emit("hhhh")
}
}
// 使用
@Component({
selector: 'club',
template: `<singleComponent (putRingOnIt)="ringWasPlaced($event)"></singleComponent>`
})
class ClubComponent {
ringWasPlaced(message: string) {
}
}
3.5.6
标记当前选中的商品
<div class="ui items">
<product-row
*ngFor="let myProduct of productList"
[product]="myProduct"
(click)='clicked(myProduct)'
[class.selected]="isSelected(myProduct)">
</product-row>
</div>
3.9 *ngFor获取当前index
<div class="product-department">
<span *ngFor="let name of product.department; let i=index">
<a href="#">{{ name }}</a>
<span>{{i < (product.department.length-1) ? '>' : ''}}</span>
</span>
</div>
3.10 创建NgModule并启动应用
@NgModule({
declarations: [
InventoryApp,
ProductImage,
ProductDepartment,
PriceDisplay,
ProductRow,
ProductsList
],
imports: [ BrowserModule ],
bootstrap: [ InventoryApp ]
})
class InventoryAppModule {}
// 启动应用
platformBrowserDynamic().bootstrapModule(InventoryAppModule);
第4章 内置指令
4.2 ngIf
<div *ngIf="false"></div>
4.3 ngSwitch
<div class="container" [ngSwitch]="myVal">
<div *ngSwitchCase="'A'">var is A</div>
<div *ngSwitchDefault>var is something else</div>
</div>
4.4 ngStyle
<div [style.background-color]="'yellow'">
uses fixed yellow background
</div>
另一种写法
<div [ngStyle]="{color: 'red', 'background-color': 'red'}"></div>
4.5 ngClass
// 是否添加某个类
<div [ngClass]="{bordered: isBordered}"></div>
或
<div [ngClass]="classObj"></div> // classObj = {bordered: true}
// 添加类的集合
<div [ngClass]="classList"></div> // classList = ['red', 'round']
4.6 ngFor
4.7 ngNonBindable