This article will give you an in-depth understanding of several special selectors in Angular: host, :host-context, ::ng-deep. I hope it will be helpful to you!
:host
:host means selecting the current component. [Recommended related tutorials: "angular tutorial"]
1.1 Select host element
Use the :host
pseudo-class selector to select elements in the component宿主元素
(relative to the elements inside the component template). If there are no child elements, it is equivalent to selecting the entire宿主元素
.
If there is the following html:
<app-detail></app-detail>
The style of the component app-detail
(the style of the entire app-detail
) is as follows:
:host { display: inline-block; background: red; }
The browser Elements
selects app-detail
element, and the Style is as follows:
[_nghost-wtd-c445] { display: inline-block; background-color: red; }
It can be seen that :host
directly acts on宿主元素本身
1.2 Select child elements of the host element
You can add a selector after :host
to select子元素
. For example: :host h1
locates the h1
tag within the component view
:host h1 { color:red; }
1.3 Conditional selection of host elements
It will only take effect when the host is used as the target and has an active class.
:host(.active){ border-width: 3px; }
Like this:
<app-detail class="active"></app-detail>
::ng-deep
::ng-deep can ignore the nested hierarchical relationship of intermediate classNames. Directly find the className you want to modify.
When using some third-party components, you need to modify the style of the component. In this case, use .
2.1 From the host element to the current element and then to all child h3 elements in the DOM, including h3 elements using third-party components in the current component
:host ::ng-deep h3 { font-style: italic; }
2.2 Search for a specific type under a certain type
.card-container ::ng-deep .ant-tabs-card .ant-tabs-content { height: 120px; margin-top: -16px; }
:host-context
If a certain condition needs to be met before the style can be applied. It looks for CSS classes in the
祖先
nodes of the current component's宿主元素
, up to the root node of the document.如果
found, the following styles will be applied to the internal elements本组件
.
3.1 Select elements in the component host element
:host-context { color:red; }
3.2 It will only take effect when the host is used as the target and has an active class.
In the following example, background-color
style will be applied to all <h2>
elements本组件内部
only if an祖先元素
(the host element can also be used) has the CSS class theme-light
.
:host-context(.theme-light) h2 { background-color: #eef; }
3.3 You can add a selector after :host-context to select sub-elements
For example: :host-context h1
locates the h1
tag inside the component view
:host-context h1{ color: hotpink; }
3.4 Can be used to judge the internal conditions of a certain style
h1{ color: hotpink; :host-context(.active) &{ color: yellow; } }