I'm totally new to web-components
and couldn't figure out which part has gone wrong.
I'm trying to create a web-component
which includes a button
, that supposed to show and hide a p
tag. Below is the code and it's working fine.
class SpecialButton extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
this._toShow = false;
this.shadowRoot.innerHTML = `
<style>
p {
display: none;
}
</style>
<button>Show</button>
<slot><p>default paragraph!</p></slot>
`;
}
connectedCallback() {
const button = this.shadowRoot.querySelector('button');
const p = this.shadowRoot.querySelector('p');
if (this.hasAttribute('toShow')) {
this._toShow = this.getAttribute('toShow');
if (this._toShow) {
button.textContent = 'Hide';
p.style.display = 'block';
this._toShow = false;
} else {
button.textContent = 'Show';
p.style.display = 'none';
this._toShow = true;
}
}
button.addEventListener('click', () => {
if (this._toShow) {
button.textContent = 'Hide';
p.style.display = 'block';
this._toShow = false;
} else {
button.textContent = 'Show';
p.style.display = 'none';
this._toShow = true;
}
});
}
}
customElements.define('uc-button', SpecialButton);
If I dont pass anything to uc-button
, it works great
<uc-button toShow="true"></uc-button>
The problem I'm facing now is I'm trying to pass a p
as slot
from my html
<uc-button toShow="true"><p>GGGGGGG</p></uc-button>
As a result, <p>GGGGGGG</p>
seems like always showing and I'm not sure which part gone wrong. Am I understand slot
wrongly, that it can only take in string but not HTML Node?
UPDATES I've created a reproducible demo @ https://codesandbox.io/s/inspiring-hill-evgol?file=/index.html
GGGGGG
`? – HoldOffHunger Sep 21 '20 at 15:14default paragraph!
GGGG
"`, instead of the component syntax, of `var1 =GGGG
;`. But I'm not sure, because I don't see that part of the code. I can elaborate this into an answer if this is correct. – HoldOffHunger Sep 21 '20 at 15:18