Noober
Noober

Reputation: 1626

:host styling not getting applied in angular6

I am trying to change the outline color for mat-form-field.

 :host /deep/ .mat-form-field-appearance-outline :host /deep/ .mat-form-field-outline {
    color: white;
}

This is however not working. Using :host seems to be the issue because the following works fine:

/deep/ .mat-form-field-appearance-outline /deep/ .mat-form-field-outline {
    color: white;
}

But if I do not use :host, this style is getting applied to other components as well. I am not sure why :host is not working.

Upvotes: 0

Views: 1755

Answers (1)

ysf
ysf

Reputation: 4854

the problem with following code is the second :host selector. because it cannot match any host element after matching .mat-form-field-appearance-outline

:host /deep/ .mat-form-field-appearance-outline :host /deep/ .mat-form-field-outline {
    color: white;
}

when second :host selector is removed it works in a way that it applies styles to current component and all of its children. (btw second /deep/ selector is also unnecessary)

following code differs from previous one in a way that, absence of :host selector makes this style truly global. so it applies all components in component tree. ie. all ancestors and children.

/deep/ .mat-form-field-appearance-outline /deep/ .mat-form-field-outline {
    color: white;
}

above concepts are explained in here

Applying the ::ng-deep pseudo-class to any CSS rule completely disables view-encapsulation for that rule. Any style with ::ng-deep applied becomes a global style. In order to scope the specified style to the current component and all its descendants, be sure to include the :host selector before ::ng-deep. If the ::ng-deep combinator is used without the :host pseudo-class selector, the style can bleed into other components.

so when you use :host /deep/ on any css selector it selects elements within current component and its children. in order prevent it affecting any children you should make your selector more specific by adding a custom class to elements you want to select and combine it with :host /deep/ selector such that;

:host /deep/ .redOutline.mat-form-field-appearance-outline .mat-form-field-outline {
    color: white;
}

and add redOutline class to mat-form-field elements you want to select.

here is a working demo https://stackblitz.com/edit/angular-qy7g4r

Upvotes: 1

Related Questions