Подтвердить что ты не робот

Angular значение привязки 2.0 к стилю

Я пытаюсь связать свойство цвета из моего класса (приобретенного привязкой атрибута), чтобы установить фоновый цвет моего 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? Что такое замена для

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

в angular 2.0?

4b9b3361

Ответ 1

Оказывается, привязка стиля к строке не работает. Решение было бы связать фон стиля.

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

Ответ 2

На данный момент (январь 2017/ 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>

Ответ 3

Мне удалось заставить его работать с 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

Попробуйте [attr.style]="changeBackground()"