Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional styling on host element

I have a component that all it does is render , its something like this:

@Component({
     selector: 'my-comp',
     host: ???,
     template: `
         <ng-content></ng-content>
     `
})

 export default class MyComp {
   @Input() title: string;
   public isChanged: boolean;
 }

The component has a isChanged property and I want to apply styling on the host element based on that isChanged property. Is this even possible?

like image 958
Bryant11 Avatar asked May 16 '16 16:05

Bryant11


People also ask

What pseudo selector or selector helps apply a style to the element that hosts the component?

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. Creating the following style will target the component's host element.

What is the host element in Angular?

To turn an Angular component into something rendered in the DOM you have to associate an Angular component with a DOM element. We call such elements host elements. A component can interact with its host DOM element in the following ways: It can listen to its events.

What is host property in CSS in Angular application?

The :host CSS pseudo-class selects the shadow host of the shadow DOM containing the CSS it is used inside — in other words, this allows you to select a custom element from inside its shadow DOM. Note: This has no effect when used outside a shadow DOM.

What does host :: ng deep means?

The ::ng-deep pseudo-class selector So this style will be applied to all h2 elements inside app-root , but not outside of it as expected. This combination of selectors is useful for example for applying styles to elements that were passed to the template using ng-content , have a look at this post for more details.


1 Answers

You use the class and style prefix for this. Here is a sample:

@Component({
  selector: 'my-comp',
  host: {
    '[class.className]': 'isChanged'
  },
  template: `
    <ng-content></ng-content>
  `
})
export default class MyComp {
  @Input() title: string;
  public isChanged: boolean;
}

See the Günter's answer for more details:

  • ngClass in host property of component decorator does not work
like image 162
Thierry Templier Avatar answered Sep 29 '22 12:09

Thierry Templier