If you want your styles to only apply to the custom field, rather than any direct usages of mat-form-field.
You can set up your custom field with normal view encapsulation (as long as you aren't using the shadow-dom)
Then you use ::ng-deep
to pierce the encapsulation.
For example one method I often use for selectors that don't select anything rendered by the component itself (ones that won't have the hash code attribute for the view encapsulation) is to select the :host
element and then do a descendant combinator from there with ::ng-deep
.
:host ::ng-deep .mat-form-field {
background: pink;
}
Note, you might need to play around with things a little and double check which styles are/aren't getting applied via the dev tools.
Background Information
:host
selects the host element. This element is what angular automatically creates as the parent of all components. It'll be kebob case component name and would be selectable via :host
which gets the current component's host element (via attribute selector), or it can generally be selected via component-name {}
as if it is a normal element.
The host element is what classes and inline styles get applied to, because Angular knows they are always there. There is also no way to avoid having a host element in Angular (there was a way back in angular.js)
::ng-deep
as mentioned is "deprecated". The problem is... there's no replacement for it. Working with other libraries while trying to encapsulate some changes, it's easy enough to keep using ng-deep. Google has never given a removal version for it despite being "deprecated", and there have been several major versions since that deprecation. From an Angular issue, it looks like they don't plan to remove ng-deep until there's a replacement.
That being said, if you really don't want to use ng-deep, then you can remove ViewEncapsulation and replace the :host ::ng-deep
by selecting the host element yourself via the host element's element selector. For example, component-name .mat-form-field{}
will select .mat-form-field
class only when a child of the host element component-name
.