5

I want to set a css variable in my TS component, and set the value to an Input(). Heres what I have that isn't working:

@HostBinding('style.--customVar') @Input() myInput = 'val';

So I want the html to look like:

<my-component style="--customVar:val"></my-component>

But my host binding does not seem to trigger. I know I have the hostBinding set up properly because if I do something like:

@HostBinding('style.backgroundColor') @Input() myInput = 'black';

It works fine. Any suggestions?

1

2 Answers 2

3

Same problem here, this solved my problem (@ Anguler 9):

@Component({...})
export class MyComponent implements AfterViewInit {

    constructor(private elementRef: ElementRef) { }

    ngAfterViewInit(): void {
        const ne = this.elementRef.nativeElement;
        ne.style.setProperty('--my-offset-top', ne.offsetTop + 'px');
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

Came across this while looking for a solution to @Hostbinding problems and had notes on your problem... (seems like Hostbinding needs some attention from the Angular team)

Dynamically set CSS variables with setProperty

https://coryrylan.com/blog/theming-angular-apps-with-css-custom-properties

const key1 = `--theme-secondary-${color.name}`;
const value1 = color.hex;

// set variable value
document.documentElement.style.setProperty(key1, value1);
CSS.registerProperty() // create new prop

An Angular specific way to access CSS

https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration

constructor(@Inject(DOCUMENT) private document: Document)

const ss = document.styleSheets[0] as CSSStyleSheet;
const rules = ss.cssRules[0] as CSSStyleRule;
console.log(rules.style.getPropertyValue('--grid-columns')); // get a prop value

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.