属性绑定
- 插值表达式:
src="{{user.pic}}"
- 使用:
[ ] :[property]="变量"
- 使用:
bind-:bind-src="变量"
// src/app/app.component.ts
export class AppComponent {
picUrl = './image/1.png';
picAlt = 'pic goode';
pic = {
url: './image/1.png',
alt: 'pic goode'
};
isUnchanged: true;
customTitle: 'custom title';
}
// src/app/app.component.html
// 使用 []
<img [src]="picUrl" [alt]="picAlt" />
<button [disabled]="isUnchanged">Disabled Button</button>
/****************** 特别提示 start *********************/
// 这样会报错
<tr><td colspan="{{1 + 1}}">Three-Four</td></tr>
// 正确写法
<tr><td [colSpan]="1 + 1">Three-Four</td></tr>
/****************** 特别提示 end **********************/
// 使用bind
<img bind-src="picUrl" bind-alt="picAlt" />
// 插值
<img src="{{ pic.url }}" alt="{{ pic.alt }}" />
// 绑定自定义属性
<span [attr.data-title]="customTitle">some words</span>
<span [attr.title]="customTitle">title</span>
class绑定
绑定单个class
//src/app/app.component.ts
export class AppComponent {
theme = 'primary';
isSuccess = true;
}
//src/app/app.component.html
<div class="btn" [class.btn-danger]="'吃吃吃吃饭'">danger</div>
<div class="btn" [class.btn-danger]="0">danger</div>
<div class="btn" [class.btn-danger]="undefined">danger</div>
<div class="btn" [class.btn-primary]="theme === 'primary'">Primary</div>
<div class="btn" [class.btn-secondary]="true">secondary</div>
<div class="btn" [class.btn-success]="isSuccess">success</div>
绑定多个class
// src/app/app.component.ts
export class AppComponent {
btnCls = 'btn btn-primary'; // 字符串,空格分隔
btnCls2 = ['btn', 'btn-success'];
btnCls3 = {
btn: true,
'btn-info': true
};
}
// src/app/app.component.html
<div class="btn" [class]="btnCls">btnCls</div>
<div class="btn" [class]="btnCls2">btnCls2</div>
<div class="btn" [class]="btnCls3">btnCls3</div>
<!-- 也可以用内置指令ngClass -->
<div class="btn" [ngClass]="btnCls">btnCls</div>
<div class="btn" [ngClass]="btnCls2">btnCls2</div>
<div class="btn" [ngClass]="btnCls3">btnCls3</div>
属性样式
样式优先级:
- 某个类或样式绑定越具体,它的优先级就越高
- 绑定总是优先于静态属性
单一样式绑定
// src/app/app.component.html
<p [style.color]="'pink'">some words</p>
<p [style.height]="'50px'" [style.border]="'1px solid'">属性值中带单位px</p>
<p [style.height.px]="50" [style.border]="'1px solid'">单位px不在属性值中</p>
多重样式绑定
// src/app/app.component.ts
export class AppComponent {
style1 = 'width: 200px;height: 50px;text-align: center;border: 1px solid;';
style2 = {
width: '200px',
height: '50px',
'text-align': 'center',
border: '1px solid'
};
}
// src/app/app.component.html
<p [style]="style1">style1</p>
<p [style]="style2">style2</p>
绑定事件
// src/app/app.component.ts
export class AppComponent {
onClick() {
console.log('onClick');
};
onClick2(event: MouseEvent) {
console.log('onClick', event.target);
};
}
// src/app/app.component.html
<!-- 不同于vue,这里需要用()来调用函数 -->
<div (click)="onClick()">btn</div>
<!-- 这里一定是$event,就是原生的事件对象-->
<div (click)="onClick2($event)">btn2</div>
<!-- 绑定方法的等号后面可以写任意js代码-->
<div ((click)="$event.preventDefault()">btn2</div>