I am currently familiarizing myself with the concept of web components.
I am trying to give the custom component a stylesheet, so that it can mimic the page content. But the argument I am trying to pass seems to be 'null' from the view of DiceComponent.js.
What I would expect to happen is:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Web Component Test</title>
<script src="DiceComponent.js"></script>
<link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body>
<p>if it works, you shall see a webcomponent below. </p>
<p>if the webcomponent manages to use the same style as the page, it should turn green!</p>
<my-diceroll component-style="style.css"></my-diceroll>
</body>
</html>
DiceComponent.js
class DiceRoll extends HTMLElement {
constructor() {
super();
const shadow = this.attachShadow({mode:'open'});
let paragraph = document.createElement("p");
paragraph.textContent = "GREEN when argument is passed, RED when not";
//style stuff
const style = document.createElement('link');
style.setAttribute('rel','stylesheet')
style.href = this.hasAttribute('component-style') ? this.getAttribute('component-style') : 'ComponentStyle.css';
shadow.append(paragraph);
shadow.append(style);
}
}
window.customElements.define('my-diceroll', DiceRoll);
style.css
p {
color: green;
}
ComponentStyle.css
p {
color: red;
}
current result from (chrome) browser:
Apparently, the arguments are not yet available in the constructor. Only after the component is added to the DOM tree.
This issue is solved by migrating the code to the connectedCallback routine, which gets called after the component is added to the DOM tree.
connectedCallback(){
const shadow = this.shadowRoot;
const style = document.createElement('link');
style.id = "style";
style.setAttribute('rel','stylesheet')
style.href = this.hasAttribute('component-style') ? this.getAttribute('component-style') : 'ComponentStyle.css';
shadow.append(style);
}