angular2多種綁定

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導入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中實現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;
    }
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容