[angular] 값을 스타일에 바인딩

나는 설정 (바인딩 속성에 의해 인수) 내 수업에서 색상 속성을 결합하기 위해 노력하고있어 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클래스 내에서 색상 속성의 변경 사항을 어떻게 볼 수 있습니까? 대체 무엇입니까

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

Angular 2에서?



답변

문자열에 대한 스타일 바인딩이 작동하지 않는 것으로 나타났습니다. 해결책은 스타일의 배경을 바인딩하는 것입니다.

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


답변

현재 (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>


답변

다음과 같이 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>


답변

  • 당신에 app.component.html 사용 :

      [ngStyle]="{'background-color':backcolor}"
    
  • 에서 app.ts 문자열 유형의 변수를 선언 backcolor:string.

  • 변수를 설정합니다 this.backcolor="red".


답변

시험 [attr.style]="changeBackground()"


답변