I’m having a problem with Lit components I’m really not able to find a solution for no matter how hard I tried.
Here’s how my <f-news-tags />
Lit component is used in Storybook:
const props = {
tags: [
{
id: '605331e873b0c322aff5cce7',
url: 'https://www.example.com/uno',
label: 'Uno',
},
{
id: '605331e873b0c322aff5cce8',
url: 'https://www.example.com/due',
label: 'due',
},
......
}
<f-news-tags>
<ul slot="list">
${
props.tags.map((tag) => html`
<f-news-tag slot="items"
id=${tag.id}
url=${tag.url}
label=${tag.label}
></f-news-tag>
`)
}
</ul>
</f-news-tags>
It basically cycles through the tags
array of objects and returns an <f-news-tag>
for each object with the object data passed to it.
Here’s how I built <f-news-tags>
:
@customElement('f-news-tags')
export default class NewsTags extends LitElement {
static override styles: CSSResultGroup = [componentStyles, styles];
static dependencies = {
'f-container': Container
};
@property({ type: String }) date: string = '12.12.2022';
@property({ type: Array, attribute: false }) tags = [];
@property({ type: Boolean }) showMore = false;
@queryAssignedElements({slot: 'items', flatten: true}) listItems!: Array<HTMLElement>;
override firstUpdated() {
console.log("This is the array of items", this.listItems);
}
override render() {
return html`
<div class="wrapper">
<f-container size="m" topspace="m" bottomspace="m">
${this.date ? html`<div class="date">${this.date}</div>` : ''}
<slot name="list">
<slot name="items"></slot>
</slot>
</f-container>
</div>
`;
}
}
And here’s how I built the single <f-news-tag>
:
@customElement('f-news-tag')
export default class NewsTag extends LitElement {
static override styles: CSSResultGroup = [componentStyles, styles];
@property({ type: String }) label = "";
//@property({ type: String }) id = "";
@property({ type: String }) url = "";
override render() {
return html`
<li class="item">
<a class="link" href="${this.url}">${this.label}</a>
</li>
`;
}
}
As you probably noticed, the is assigned to the ‘list’ slot and all <f-news-tag>
items inside the are assigned to the ‘items’ slot.
In <f-news-tags>
, I’m trying to use the @queryAssignedElements (I’ve also already tried @queryAssignedNodes) decorator to get an array of the elements inside the ‘items’ slot. What I’m trying to achieve with this is to be able to conditionally render a show more/show less button when the cycled items exceed a given number. Despite all my efforts, however, the resulting listItems array is always empty.