92

background-colorクラスから色プロパティをバインドして (属性バインディングによって取得) 、 myの を設定しようとしていdivます。

import {Component, Template} from 'angular2/angular2';

@Component({
  selector: 'circle',
  bind:{
    "color":"color"
  }
})
@Template({
  url: System.baseURL + "/components/circle/template.html",
})
export class Circle {
    constructor(){

    }

    changeBackground():string{
        return "background-color:" + this.color + ";";
    }
}

私のテンプレート:

<style>
    .circle{
        width:50px;
        height: 50px;
        background-color: lightgreen;
        border-radius: 25px;
    }
</style>
<div class="circle" [style]="changeBackground()">
    <content></content>
</div>

このコンポーネントの使用法:

<circle color="teal"></circle>

バインディングが機能していませんが、例外もスローされません。

テンプレートのどこかに配置{{changeBackground()}}すると、正しい文字列が返されます。

では、なぜスタイル バインディングが機能しないのでしょうか。

Circleまた、クラス内の color プロパティの変更をどのように監視しますか? 代わりになるものは何ですか

$scope.$watch("color", function(a,b,){});

角度2で?

4

6 に答える 6

44

現在 (2017 年 1 月 / Angular > 2.0) では、以下を使用できます。

changeBackground(): any {
    return { 'background-color': this.color };
}

<div class="circle" [ngStyle]="changeBackground()">
    <!-- <content></content> --> <!-- content is now deprecated -->
    <ng-content><ng-content> <!-- Use ng-content instead -->
</div>

最短の方法はおそらく次のようになります。

<div class="circle" [ngStyle]="{ 'background-color': color }">
    <!-- <content></content> --> <!-- content is now deprecated -->
    <ng-content><ng-content> <!-- Use ng-content instead -->
</div>
于 2017-01-11T01:01:19.883 に答える