Angular:内容投影场景下将颜色属性传入SVG组件SCSS样式
Absolutely! You can absolutely pass the parent component's color property down to your SVG component and use it in your SCSS styles—here are a couple of clean, Angular-friendly ways to pull this off:
Method 1: Use CSS Custom Properties (Recommended)
This approach is super flexible and plays nicely with SCSS, letting you reuse the color across multiple SVG elements without repeating code:
Add an Input to Your SVG Component
In yourlogo.ts(SVG component class), define an@Input()to accept the color from the parent:import { Component, Input } from '@angular/core'; @Component({ selector: 'app-svg-logo', templateUrl: './logo.component.html', styleUrls: ['./logo.component.scss'] }) export class LogoComponent { @Input() color: string = '#000000'; // Default to black if no color is passed }Bind the Color to a CSS Variable in the SVG Template
In your SVG component's template (logo.component.html), set a CSS custom property on the root<svg>element using Angular's style binding:<svg [style.--svg-fill-color]="color" viewBox="0 0 24 24"> <!-- Your SVG elements (path, circle, etc.) go here --> <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2z"/> </svg>Use the CSS Variable in Your SCSS
Now you can reference this variable directly in your SCSS styles to set fill/stroke colors for SVG elements:svg { path, circle, rect { fill: var(--svg-fill-color); // Use stroke: var(--svg-fill-color); if you need to style strokes instead } }
Method 2: Direct Style Binding (Simpler for Single Elements)
If you only need to style one or two SVG elements, you can skip CSS variables and bind the color directly to the element's fill or stroke attribute:
Same Input Setup as Method 1
Keep the@Input() colorin yourlogo.tsfile.Bind the Color to SVG Elements
In your SVG template, use Angular's attribute binding to set the color on specific elements:<svg viewBox="0 0 24 24"> <path [attr.fill]="color" d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2z"/> </svg>
Quick Notes
- If you're using content projection to include the SVG component in a parent, make sure you pass the
colorattribute directly to the SVG component tag, like this:<!-- Parent component template --> <div class="parent-container"> <app-svg-logo color="white"></app-svg-logo> </div> - For SVGs with multiple elements that need different colors, you can extend the CSS variable approach by adding multiple inputs (e.g.,
@Input() fillColorand@Input() strokeColor) and corresponding variables.
内容的提问来源于stack exchange,提问作者Snorlax

