angular - 将 View 封装 id 选择器从父级传递给 @Input css 类

标签 angular

好的,所以我们知道了ng-deep这不是最佳实践,我们知道 ViewEncapsulation.None变得恶心。所以这是我的问题,我想做的是这个。

假设我有一个组件;

@Input() cssClasses: string;

然后在使用它的父组件上我做了类似的事情;

<my-component [cssClasses]="some-css-class some-other-css-class"></my-component>

现在,在传递这些类的地方,我想将组件生成的选择器 ID 附加到这些类,以便在 DOM 中呈现时,它们与使用组件的 css 类匹配,就像我们从子组件看到的输出一样;

<div class="class1 class2 some-css-class some-other-css-class"></div>

这里的问题显然是 viewEncapsulation 会将组件 id 选择器附加到组件中的类,而不是传递给它的类。所以没有 ng-deep或者将这些类放在顶级初始 css 文件中,它们将不会被应用,因为选择器是这样出现的;

[_ngStuff-blah-123] .class1 {...}
[_ngStuff-blah-123] .class2 {...}

但是自some-css-class some-other-css-class永远不会从通过 @Input 派生的 css 类中获取 id 选择器他们实际上并没有应用的 child 。除非他们宣布你有 ng-deep或者如果它位于未附加到其他组件或其他任何组件的顶级 css 中。

如何附加消费组件的上下文,以便最终得到类似这样的输出;

[_ngStuff-blah-123] .class1 {...}
[_ngStuff-blah-123] .class2 {...}
[_ngStuff-parent-999] [_ngStuff-blah-123] .some-css-class {...}
[_ngStuff-parent-999] [_ngStuff-blah-123] .some-other-css-class {...}

而不是仅仅使用 ngStyle , ng-deep ,还是顶层开始?

有没有办法在使用子组件时做一些事情,比如;

<my-component [cssClasses]="some-css-class some-other-css-class" [hostContext]="this.parent.idContext"></my-component>

因此 DOM 输出看起来像上面的示例,我们可以在没有 ng-deep 的情况下利用一些特定于实例的类传递ETC?如果这是重复的,我当然不是第一个这么道歉的人。

最佳答案

您想使用 host-context 来根据父级中的 CSS 类设置子级的样式,而无需传入这些类。本质上它的工作方式与此类似。这是子组件中的 CSS:

:host-context(.wrapper-blue) .hello {
  color: blue
}

:host-context(.wrapper-red) .hello {
  color: red
}

子元素中的 HTML:

<div class="hello">
  hello <!-- color depends on the class wrapping me in the parent -->
</div>

父级中的 HTML 如下所示:

<div class="wrapper-red">
 <app-child-component><app-child-component>
</div>

<div class="wrapper-blue">
 <app-child-component><app-child-component>
</div>

自从我使用它以来已经有一段时间了,所以我的语法可能有点不对劲,但你明白了。 Google Angular host-context,你会找到你需要的。或者在此处查看这些 SO 帖子:

What is the use case of :host-context selector in angular

Cannot Understand the Use of :host in components in Angular2

这里的帖子不错,看起来比其他的好:

https://blog.angular-university.io/angular-host-context/#thehostcontextpseudoclassselector

这是官方docs这证明它没有被弃用!

关于angular - 将 View 封装 id 选择器从父级传递给 @Input css 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70027521/

相关文章:

javascript - 将 SVG.select() 方法与 svg.js 库的类选择器一起使用不适用于 typescript

angular - 为什么在 API 调用上使用 Angular 服务更好?

Angular v8 - @ViewChild 静态真或假

javascript - 如何检测 Angular2 中 Date 对象的变化?

node.js - 命令问题 - "ng"命令未被识别为内部或外部命令,即使位于 PATH 环境变量中也是如此

Angular 6 View 不更新,即使使用 ChangeDetectorRef、ngZone 和 requestAnimationFrame

angular - 如何将angular5应用程序部署到子目录

Angular2 - 'then' 在类型 'void' 上不存在

iframe - 更改 Angular 2中iframe内元素的属性

arrays - 使用 *ngFor (Angular 4) 遍历 JSON 对象数组