How do I dynamically change CSS properties of a component host?
I have a component and in it's CSS I have given it a stlye:
:host {
overflow-x: hidden
}
On a button click from child component, I need to add overflow-y: hidden
to the host component.
How do I achieve this behavior?
Using ngClass Here we can set the buttonClass to any string, and use that string to our button element as a class. As long as we have a valid selector in our SCSS (i.e. . secondary ), this will dynamically change the styling of our button component.
create a new component and create a service to load dynamic css variables from API. Add style tag in template file and use variable values for properties. Load this template on all pages or on main template. On app build style will be moved to head tag.
Every component is associated within an element that matches the component's selector. This element, into which the template is rendered, is called the host element. The :host pseudo-class selector may be used to create styles that target the host element itself, as opposed to targeting elements inside the host.
Here is a working example.
Use the following HostBinding:
@HostBinding('style.overflow-y') overflowY = 'scroll';
This would give the following component:
@Component({
selector: 'my-app',
template: `
<div>
<button (click)="addStyle()">Add Style</button>
<h2>Hello</h2>
</div>`, styles: [
`
:host {
overflow-x: hidden;
height: 50px;
width: 200px;
display: block;
}
`,
],
})
export class App {
name: string;
@HostBinding('style.overflow-y')
overflowY = 'scroll';
constructor() {
}
addStyle() {
this.overflowY = 'hidden';
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With