Miguel Moura
Miguel Moura

Reputation: 39354

Apply CSS class to component's child elements

I have the following component's HTML (StackBlitz Example):

<div class="measure">
  <ng-container *ngTemplateOutlet="labelTemplate; context: templateContext"></ng-container>
  <div class="chart">
    <div class="state" [style.width.%]="progress">&nbsp;</div>
  </div>
  <ng-container *ngTemplateOutlet="valueTemplate; context: templateContext"></ng-container>
</div>

And I am using it as follows:

<mk-progress class="test" [minimum]="0" [maximum]="100" [current]="40">
  <div *label class="label">Label</div>
  <div *value="let item" class="value">{{ item.progress }}%</div>
</mk-progress>

I need to apply css styles to mk-progress child elements when mk.progress has class test:

:host(.test) div.measure {
  border: 1px solid orange;
}

:host(.test) div.label {
  border: 1px solid red;
}

:host(.test) div.value {
  border: 1px solid green;
}

The border is applied to measure but not to label and value. Why

Upvotes: 1

Views: 724

Answers (1)

jo_va
jo_va

Reputation: 13964

Use the ::ng-deep shadow-piercing descendant combinator for that (angular doc here):

:host(.test) ::ng-deep div.label {
  border: 1px solid red;
}

:host(.test) ::ng-deep div.value {
  border: 1px solid green;
}

This is a deprecated, but there is however no real substitute for it, see this SO post about it.

Long story short: Keep using ::ng-deep and its alternatives until a replacement is created - the deprecation is just an early notice so that people aren't blindsided whenever the actual change materializes.

Upvotes: 3

Related Questions