Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing data to the styles component angular2

Tags:

css

angular

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>
like image 893
Sajad Avatar asked Mar 21 '26 04:03

Sajad


2 Answers

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>`,
like image 128
Günter Zöchbauer Avatar answered Mar 23 '26 19:03

Günter Zöchbauer


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.

like image 42
rivanov Avatar answered Mar 23 '26 19:03

rivanov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!