Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically change CSS in :host in angular 2?

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?

like image 872
code1 Avatar asked May 22 '17 20:05

code1


People also ask

How do you set dynamic style in angular 12?

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.

How do I use dynamic CSS in angular 6?

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.

What is host selector in angular?

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.


1 Answers

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';
    }
}
like image 127
Julia Passynkova Avatar answered Oct 11 '22 13:10

Julia Passynkova