1
votes

In Angular 2+ I need to pass value stored in component variable to CSS top property used in one of :before styles. In this case I cannot use [ngStyle] directly because it doesn't allow to access CSS pseudo selectors. I've tried to use it to affect CSS variable like this:

HTML:

<div class="summaries-graph-box">
     <div class="summaries-graph">
          <div [ngStyle]="{'--odds-top-height': graphOddsTopHeight + 'px'}" 
               class="summary-graph-column summary-plan summary-odds">
                  <span class="summary-value">123</span>
          </div>                 
      </div>
</div>

TS:

graphOddsTopHeight = 40;

and in CSS I'm using:

 .summary-odds {
    --odds-top-height: 20px;
 }

  .summary-odds:before {
      min-height: 30px;
      top: var(--odds-top-height);
  }

The CSS variable is working however the value is still 20px (which is originally set within CSS) not 40px (provided from component variable).

I've also tried to use attr like this:

HTML:

 <div [attr.odds-top-height]="graphOddsTopHeight + 'px'" 
      class="summary-graph-column summary-plan summary-odds">
          <span class="summary-value">123</span>
 </div>                

and then in CSS:

summary-odds:before {
    top: attr(odds-top-height);
}
//or
summary-odds:before {
    top: attr(data-odds-top-height);
}

However in this case the browser simply ignores top property and crosses it out.

Does anyone have an idea what is wrong with my code or what else I can do to pass variable from component to CSS :before pseudo selector?

1

1 Answers

2
votes

You should use the binding directive, something like this:

<div class="summaries-graph-box">
     <div class="summaries-graph">
          <div [style.height.px]="getSummaryHeight(summary.Plan)" 
               class="summary-graph-column summary-plan summary-odds">
                  <span class="summary-value">123</span>
          </div>                 
      </div>
</div>

And your function on .ts:

getTheRightHeight();

Should return a number value, for example: 40. (not 40px, just 40)

--UPDATE
If you still want to access the variable or the css, You can do it with something like:

@ViewChild("myDiv") myDiv: ElementRef;

and then you can access the div properties via this.myDiv.nativeElement and access the style property of the variable
(<HTMLDivElement>this.myDiv.nativeElement).style.setProperty('--YouCSSVariable', YourNewValue)
like in Javascript