angular2多种绑定

angular提供绑定机制,解决mode-view耦合。

先看下Demo运行效果

angular2多种绑定_第1张图片
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

{{name}}

data双向绑定

在app.module.ts导入FormsModule

import { FormsModule } from '@angular/forms';

@NgModule({
    imports: [BrowserModule,FormsModule],
    ...

修改app.component.html

{{name}}

name:

事件绑定

app.component.html尾部新增


app.component.ts中实现changeTitle()方法

changeTitle(): void {
    this.name="sider";
}

style简单绑定

app.component.html

{{name}}

app.component.ts

isStatic(): Boolean {
    return this.name === 'static';
}

style组合绑定

app.component.html


# 

{{name}}

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

{{name}}

  • ngClass

app.component.html




{{name}}

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;
    }

你可能感兴趣的:(angular2多种绑定)