Willem van Gerven
Willem van Gerven

Reputation: 1587

Angular 2 component styles from input

We can use interpolation to write an input into the template:

@Component({
    selector: 'tag',
    inputs: ['color'],
    template: `
        <div id="test" style="background: {{color}}">
            Some text
        </div>
    `,  
})
class TestComponent {
}

My question is: Is it possible to get it (somehow) to work like this:

@Component({
    selector: 'tag',
    inputs: ['color'],
    template: `
        <div id="test">
            Some text
        </div>
    `,  
    styles: ['#test { background: {{color}}; }'],
})
class TestComponent {
}

This last attempt does not work, and I cannot seem to find a way how to do it.

Thanks.

Upvotes: 5

Views: 7335

Answers (1)

Pankaj Parkar
Pankaj Parkar

Reputation: 136144

AFAIK you can't do that. Component styles metadata wouldn't have access to its Class variable. I'd better suggest you to go for ngClass/ngStyle

<div id="test" [ngStyle]="{ 'background': color }">
    Some text
</div>

Upvotes: 4

Related Questions