css – 无法理解Angular2中组件的使用:host

前端之家收集整理的这篇文章主要介绍了css – 无法理解Angular2中组件的使用:host前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_403_1@我对host的理解是,如果我在父组件中有子组件,并且我们想要从父组件设置子组件,我们可以使用:host.
和:host-context反之亦然.
如果这是主机的正确使用,请告诉我.

https://angular.io/docs/ts/latest/guide/component-styles.html

当我尝试在我的应用程序中执行相同操作时,它会起作用

应用组件模板

<div class ="top">
    <h1>
      Home Component
    </h1>
    <hr>
    <app-ngrx></app-ngrx>
    <router-outlet></router-outlet>
  <div>

ngrx组件模板

<h3 class="mine">NGRX</h3>

<button (click)="increment()">Increment</button>
<div>Current Count: {{ counter | async }}</div>
<button (click)="decrement()">Decrement</button>

<button (click)="reset()">Reset Counter</button>

应用程序组件CSS

:host(.mine){
  color:red;
}

这似乎不起作用请帮助我无法理解.

我看了这个问题但是却无法搞清楚

Angular 2: How to style host element of the component?

@Gunter答案后更新

在我的app-ngrx模板中,我添加

<h3 class = "mine">NGRX</h3>

<button (click)="increment()">Increment</button>
<div>Current Count: {{ counter | async }}</div>
<button (click)="decrement()">Decrement</button>

<button (click)="reset()">Reset Counter</button>

在我添加的app-ngrx css文件

:host(.mine){
  color:red;
}

但即使没有添加我的应用程序组件,如

<app-ngrx></app-ngrx>

h3是红色的,因为我觉得它应该是红色的< app-ngrx class =“mine”>< / app-ngrx>

解决方法

What i have understood of host is that if i have a child component
inside a parent component and we want to style a child component from
the parent component we can use :host . and :host-context for
vice-versa

不,这不是它的用途.

:主机选择器来自shadow DOM spec.

…This scoped subtree is called a shadow tree. The element it’s
attached to is its shadow host.

在角度世界中,组件的模板是阴影树.组件的元素是影子主机.因此,当您为:host选择器定义样式时,样式将应用于组件的元素.

:主办

在您的示例中,如果您在my-app组件中定义了样式,则样式将应用于< my-app> DOM元素.这个特殊的配置:

:host(.mine){
  color:red;
}

将应用于具有.mine类的主机元素:

<my-app class="active">

如果您在app-ngrx组件中定义了样式,则样式将应用于< app-ngrx> DOM元素,不是< my-app>.这个特殊的配置:

:host(.mine){
  color:red;
}

将应用于具有.mine类的主机元素:

<app-ngrx class="active">

:主机上下文

现在,:host-context也应用于host元素,但是函数(括号)采用的选择器不是针对主机元素本身,而是针对所有祖先直到文档根目录.如果找到此元素,则应用样式.

例如,这个选择器

:host(.mine){
  color:red;
}

匹配这样的结构:

<my-app class="mine">

而,这个选择器:

:host-context(.mine){
  color:red;
}

匹配此结构:

<div class="mine">
 ...
   <my-app>

如果要有条件地将样式应用于组件视图(阴影根),这很有用.这使得h2始终是粗体:

h2 {
   font-weight: bold;
}

而这个

:host-context(.make-inner-components-bold) h2 {
  font-weight: bold;
}

仅当您的组件位于具有.make-inner-components-bold类的元素内时才使它们变为粗体.

原文链接:https://www.f2er.com/css/217818.html

猜你在找的CSS相关文章