Dark star
Dark star

Reputation: 5872

passing data to the styles component angular2

How can I pass data from angular tag to the styles in the @Component?

Here is my component:

import { Component, Input } from '@angular/core';

@Component({
  selector: 'icon',
  template: `<svg class="icon"><use attr.xlink:href="#{{name}}"></use></svg>`,
  styles: ['.icon{width:{{size}}px;}'] 
})
export class IconComponent {
  @Input() name: string;
  @Input() size: any; 

  constructor() { }

}

I wanna set size property from component.

used in html file:

<icon name="logo" size="37"></icon>

Upvotes: 3

Views: 4165

Answers (2)

rivanov
rivanov

Reputation: 1274

I'm actually surprised that I finally found a somewhat solid solution to this using a ngx-css-variables.

My use case is that I have a 3rd-party library, which creates many child components within itself, as it draws charts.

I needed to set the linear gradient with a url(#<uuid>).

CSS Template

  /deep/ngx-charts-line-chart {
  display: flex;
  /deep/ngx-charts-chart {
    display: flex;
    div.ngx-charts-outer {
      display: flex;
      svg {
        .line {
          stroke: var(--gradient);
          stroke-width: 4px;
        }
      }
    }
  }
}

Component

import * as uuid from 'uuid/v4';
...
  private _linearGradientId = uuid();
  get uuid() {
    return this._linearGradientId;
  }
  get gradientCss() {
    return {
      '--gradient': `url(#${this.uuid})`
    }
  }
...

HTML Template

...
<ngx-charts-line-chart
  [css-vars]="gradientCss"
...
<ngx-charts-line-chart>

You still have to deep style the component since it's components are not in your template, but ngx-css-variables will inject a function into the style property, which seems hacky, but it works!

So now the stroke comes from that dynamic function at runtime. Super cool. I wish angular supported this natively.

Upvotes: 1

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 658077

Binding in styles is not supported. You can use style binding like

template: `<svg class="icon" [style.width.px]="size"><use attr.xlink:href="#{{name}}"></use></svg>`,

Upvotes: 3

Related Questions