値をスタイルにバインドする


84

クラスのcolorプロパティ(属性バインディングによって取得)をバインドして、background-colorのを設定しようとしてい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,){});

Angular 2では?

回答:


108

文字列へのスタイルのバインドが機能しないことが判明しました。解決策は、スタイルの背景をバインドすることです。

 <div class="circle" [style.background]="color">

1
alligator.io/angular/style-binding-ngstyle-angularの 時点で見積もりを見逃しました<div class="circle" [style.background]="'color'">
SaadBenbouzid18年

1
わかりやすくするためにcolor、この場合は、使用する値を含むコンポーネントのプロパティです。使用したい値である引用符を使用している場合。color有効なCSSカラーではありません。のようなものである必要があり[style.background] = "'#f3f3f3'"ます。
SeanH

41

現在(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>

23

私はそれを次のようにalpha28で動作させることができました:

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

@Component({
  selector: 'circle', 
  properties: ['color: color'],
})
@View({
    template: `<style>
    .circle{
        width:50px;
        height: 50px;
        border-radius: 25px;
    }
</style>
<div class="circle" [style.background-color]="changeBackground()">
    <content></content>
</div>
`
})
export class Circle {
    color;

    constructor(){
    }

    changeBackground(): string {
        return this.color;
    }
}

このように呼んだ <circle color='yellow'></circle>


4
  • あなたにapp.component.html使用:

      [ngStyle]="{'background-color':backcolor}"
    
  • app.ts文字列型の変数を宣言しますbackcolor:string

  • 変数を設定しますthis.backcolor="red"


2

試してみてください [attr.style]="changeBackground()"

弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.