1、angular2 ng-reflect前缀去除
angular2中会有大量属性带有ng-reflect
只需要在 /src/environments/environment.ts 中设置 production: true 即可。
2、类型转换
ts转成js后,不会对输入值做类型检查
所以下列参数传入肯定是字符串
@Input()
set yuDisabled(isDisabled: boolean) {
this.disabled = coerceBooleanProperty(isDisabled);
this.updateClassNames();
}
需要引入@angular/cdk包
并且使用@angular/cdk/coercion下的
import {
coerceArray, // 转成数组
coerceBooleanProperty, // 转成布尔值
coerceNumberProperty, // 转成数字
_isNumberValue // 判断是否是数值
} from "@angular/cdk/coercion";
上面这个转换有什么用呢?
因为输入都是相当于attributes输入,是字符串。根据attributes的规则,空字符串是true,通过coerceBooleanProperty转换,只有false字符串才是false,其余全部是true
3.获取组件内容
<ng-content></ng-content>
相当于vue中的<slot></slot>
4.管道
<p>{{address | json}}</p>
5.事件绑定
<date-picker (clcik)="statement()"></date-picker>
6.路由
import { Routes, RouterModule } from '@angular/router';
export const ROUTES: Routes = [
{ path: 'user', component: UserComponent }
];
@NgModule({
imports: [
BrowserModule,
RouterModule.forRoot(ROUTES)
],
// ...
})
<a routerLink="/user">我的</a>
7.定义变量,获取DOM元素
方式一
<div>
<input #myInput type="text">
<button (click)="onClick(myInput.value)">点击</button>
</div>
方式二
<input ref-myInput type="text">
8.获取事件对象
$event名字不可改变,但顺序可以变
<button (click)="onClick($event, myInput.value)">点击</button>
9.注入服务
注入方式一:
constructor(private mailService: MailService) {}
注入方式二:
constructor(@Inject(MailService) private mailService) {}
一般type类型的直接用方式一,非type类型的用方式二
10.循环遍历 *ngFor
<li *ngFor="let message of mailService.messages; index as i;">
{{i}} - {{message}}
</li>
除了index as i,还有
first: boolean —— 若当前项是可迭代对象的第一项,则返回 true
last: boolean —— 若当前项是可迭代对象的最后一项,则返回 true
even: boolean —— 若当前项的索引值是偶数,则返回 true
odd: boolean —— 若当前项的索引值是奇数,则返回 true
10.Input装饰器
获取元素属性的message值
@Input() message: string;
如果希望元素属性的name和获取后赋值的变量名称不同
@Input('message') msg: string;
11.双向绑定和意向绑定
双向[(ngModel)]
<input #myInput type="text" [(ngModel)]="message">
单向[ngModel]
<input #myInput type="text" [ngModel]="message">
12.Output 装饰器
用来实现子组件将信息,通过事件的形式通知到父级组件
子组件
(update)="onUpdate(message.id, $event.text)"
@Output() update = new EventEmitter<{text: string}>();
父组件
onUpdate(id, text) {
this.mailService.update(id, text);
}
13.动态改变className
[ngClass]="{mousedown: isMousedown}"
14.动态改变style
[ngStyle]="{color: 'white', 'background-color': 'blue'}"