Angular——:host 和::deep

        在Angular中,:host和::ng-deep是用于在组件样式中选择和修改宿主元素和子组件的特殊选择器。

        :host是一个CSS伪类选择器,用于选择当前组件的宿主元素。它常用于在组件样式中应用样式到组件外部的宿主元素上。例如:

:host {
  background-color: blue;
}

        ::ng-deep是一个特殊的CSS伪类选择器,用于穿透组件样式影响子组件的选择器。它允许在父组件的样式中选择并修改子组件的样式。例如:

:host ::ng-deep .child-component {
  color: red;
}

        在实际开发运用中,两个选择器往往一起使用。尤其是在修改项目中运用到的UI框架的本身样式,需要渗透层级进行样式修改,又同时需要保证不能污染其他组件的样式,这个时候两者经常会一起出现。

//1. 首先使用:host选择器修改组件宿主(父)元素的样式:

:host {
  display: block;
  padding: 10px;
  background-color: #f1f1f1;
}

//2. 然后使用::ng-deep选择器修改子组件的样式:

:host ::ng-deep .child-component {
  font-weight: bold;
  color: red;
}

        但是出于样式封装和组件间的隔离考虑,建议避免滥用::ng-deep选择器。在尽可能的情况下,推荐使用组件样式继承和投影

  • 组件样式继承

        组件样式继承是将样式从父组件传递到子组件的一种方式。这可以通过在子组件中使用:host-context伪类选择器并将其与父组件css类名或属性绑定来实现。例如,如果我们想将父组件的一些样式传递给子组件,可以在子组件中使用host-context选择器,如下所示:

        在下面示例中,子组件的:host-context选择器绑定到父组件的.container类名,这意味着只有当子组件被包含在具有.container类的元素中时,子组件才会应用这些样式。

父组件模板:

<div class="container">
  <app-child-component></app-child-component>
</div>

父组件样式:

.container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

子组件样式:

:host-context(.container) {
  background-color: red;
  padding: 10px;
}
  • 组件投影

        组件投影是在组件中将其父级html内容(包括html和css)插入到组件的特定区域的技术。组件投影通过Angular的内容投影机制来实现,常见的方式有ng-contentng-template。例如,假设我们有一个父组件和一个子组件,父组件需要将一些内容(例如html标记和样式)投射到子组件,可以使用如下方式:

        在下面示例中,父组件中的html内容将被投射到子组件中。子组件中的ng-content元素表示一个插槽,可以选择父组件传递的html内容。投影到子元素中的样式定义在父组件中,可以直接应用到特定选择器(例如.important)。

父组件模板:

<app-child-component>
  <h2>这是标题</h2>
  <p>这是一些文本</p>
  <p class="important">这是一个重要信息</p>
</app-child-component>

父组件样式:

h2 {
  color: blue;
}

.important {
  font-weight: bold;
}

子组件模板:

<div class="header">
  <ng-content select="h2"></ng-content>
</div>
<div class="body">
  <ng-content select="p"></ng-content>
  <div class="important-info">
    <ng-content select=".important"></ng-content>
  </div>
</div>

猜你喜欢

转载自blog.csdn.net/qq_44327851/article/details/135182950