angular提供綁定機制,解決mode-view耦合玻靡。
先看下Demo運行效果
1111.gif
data單向綁定
app.component.ts
import { Component } from '@angular/core';
@Component({
moduleId: module.id,
selector: 'my-app',
templateUrl: 'app.component.html'
})
export class AppComponent {
name: string = "static";
}
app.component.html
<h2>{{name}}</h2>
data雙向綁定
在app.module.ts導(dǎo)入FormsModule
import { FormsModule } from '@angular/forms';
@NgModule({
imports: [BrowserModule,FormsModule],
...
修改app.component.html
<h2>{{name}}</h2>
name:<input [(ngModel)]="name" placeholder="name" />
事件綁定
app.component.html尾部新增
<button (click)="changeTitle()">change</button>
app.component.ts中實現(xiàn)changeTitle()方法
changeTitle(): void {
this.name="sider";
}
style簡單綁定
app.component.html
<h2 [style.color]="isStatic() ? 'red':'blue'">{{name}}</h2>
app.component.ts
isStatic(): Boolean {
return this.name === 'static';
}
style組合綁定
app.component.html
<!--<h2 [style.color]="isStatic() ? 'red':'blue'">{{name}}</h2>-->
# <h2 [ngStyle]="setStyles()">{{name}}</h2>
app.component.ts
setStyles(): Object {
let styles = {
'color': this.isStatic() ? 'red' : 'blue',
'font-size': this.isStatic() ? '3rem' : '2rem',
'font-style': this.isStatic() ? 'italic' : 'normal'
};
return styles;
}
class綁定
新增app.component.css文件且在app.component.ts引用
@Component({
moduleId: module.id,
selector: 'my-app',
templateUrl: 'app.component.html',
styleUrls: ['app.component.css']
})
- class
app.component.css
.awestatic {
color: red;
}
app.component.html
<h2 [class.awestatic]="isStatic()">{{name}}</h2>
- ngClass
app.component.html
<!--<h2 [style.color]="isStatic() ? 'red':'blue'">{{name}}</h2>-->
<!--<h2 [ngStyle]="setStyles()">{{name}}</h2>-->
<!--<h2 [class.awestatic]="isStatic()" [class.awesider]="!isStatic()">{{name}}</h2>-->
<h2 [ngClass]="setClasses()">{{name}}</h2>
app.component.css
.awestatic {
color: red;
font-style: italic;
}
.awesider {
color: blue;
font-style: normal;
}
.move {
position: relative;
-webkit-animation: move 1s infinite;
-webkit-animation-duration: 3s;
}
@-webkit-keyframes move {
0% {
left: 0px;
}
50% {
left: 200px;
}
100% {
left: 0px;
}
}
app.component.ts
setClasses(): Object {
let classes = {
awestatic: this.isStatic(),
awesider: !this.isStatic(),
move: !this.isStatic()
};
return classes;
}