13

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?

Omri Luzon
  • 3,975
  • 6
  • 20
  • 29
code1
  • 8,351
  • 8
  • 27
  • 31

2 Answers2

29

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';
    }
}
DuGabiche
  • 93
  • 2
  • 8
Julia Passynkova
  • 17,256
  • 6
  • 33
  • 32
1

If the button changes something in the component source, you can also use :has(..) pseudoselector.

eg.

:host:has(".someclassinside"){...}
oio154
  • 11
  • 2