样式化WebComponent中的默认插槽 [英] Styling default slot in webcomponents
问题描述
在webcomponents中,我们有两种类型的插槽(命名插槽和默认插槽)。我们可以使用语法 slot [name] :: slotted(*)
轻松设置命名插槽的样式。但是,有没有办法设置默认插槽的样式,因为它们没有任何关联的名称?
In webcomponents, we have two type of slots (named slots and default slots). We can easily style named slots by using syntax slot[name]::slotted(*)
. But is there any way that we can style default slots because they don't have any name associated?
代码是这样的,我正在使用Angular Elements。
The code is something like this and i'm using Angular Elements.
<div class="topbar-item">
<slot class="icon" name="icon"></slot>
<span class="text">
<slot></slot> <-- This is the slot i want to add styles, only if the slot has some data assigned. (need to add margin-left)
</span>
</div>
推荐答案
找到了一些解决方法,直到有人找到更好的方法。我们可以使用 slotchange 事件来确定是否有任何项目附加到该插槽。
Found a little workaround until someone finds a better way. We can use slotchange event to make sure whether any items attached to the slot or not. In this way.
HTML
<slot (slotchange)="onSlotChanged($event)"></slot>
JS / TS
onSlotChanged($event) {
const slotHasData = $event.target.assignedNodes().length > 0;
// Is event.target.assignedNodes().length return more than 0, it has nu of items attached to the slot
}
这篇关于样式化WebComponent中的默认插槽的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!