gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 17:08:21 25 4
gpt4 key购买 nike

好的,所以我们知道了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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com