Angular 2+组件中如何将TS文件的值传递至SCSS文件?
Hey there! The key thing to understand here is that SCSS (and all CSS flavors) can’t directly access dynamic values from your TypeScript code. Styles are processed statically at build time, while your outageCount is set dynamically at runtime when your API call resolves. But we can get around this by binding the TS value to a DOM attribute, then having our SCSS read that attribute. Here's how to do it:
Step 1: Bind your TS value to a custom DOM attribute
First, we need to attach the outageCount value to the element you’re targeting (app-settings-panel) as a custom data attribute. You can do this directly in your component template, or use @HostBinding if you’re targeting the component’s host element.
Option 1: Template binding
Add this to your component’s template:
<app-settings-panel [attr.data-outage-count]="outageCount || ''"></app-settings-panel>
The || '' ensures we pass an empty string if outageCount is 0 or undefined, which we’ll use later to hide the badge when there are no outages.
Option 2: HostBinding (if targeting the component's host)
If you need the attribute on the component’s own host element instead of app-settings-panel, update your TypeScript code like this:
import { Component, OnInit, HostBinding } from '@angular/core'; export class myComponent implements OnInit { private outageCount; // Bind the value to a custom data attribute on the host element @HostBinding('attr.data-outage-count') get outageCountAttr() { return this.outageCount || ''; } ngOnInit(){ ....subscribe((data) => { this.outageCount = Object.keys(data).length; }) } }
Step 2: Update your SCSS to read the attribute
Now modify your SCSS to pull the value from the custom data-outage-count attribute using the attr() function. We’ll also add a rule to hide the pseudo-element when the attribute is empty:
:host ::ng-deep app-settings-panel { position: relative; /* Ensure the pseudo-element positions correctly relative to this element */ &:before{ content: attr(data-outage-count); background: #941313; position: absolute; top: 3px; left: 22px; border-radius: 50%; height: 13px; width: 13px; border: 1px solid #ffffff; color: white; font-size: 8px; text-align: center; /* Hide the badge when there's no count */ visibility: visible; opacity: 1; transition: visibility 0s, opacity 0.2s linear; } /* Target the pseudo-element when the attribute is empty */ &:before:empty { visibility: hidden; opacity: 0; } }
Why your original code didn’t work
Your initial attempt used content: attr(outageCount);, but outageCount isn’t a DOM attribute—it’s just a variable in your TypeScript file. The attr() function only reads attributes that exist in the rendered HTML, so we needed to explicitly bind the TS value to a DOM attribute first.
内容的提问来源于stack exchange,提问作者Ramya S

