We can have stencilJS element with slot
as below
<my-ponent>123</my-ponent>
I'm trying to get the value of 123
from my render
method itself, wondering if that is possible?
@Component({ tag: 'my-ponent' })
export class MyComponent {
render() {
return (
<div><slot /></div>
)
}
}
I would like to do some string formatting on 123
instead of rendering slot
directly
We can have stencilJS element with slot
as below
<my-ponent>123</my-ponent>
I'm trying to get the value of 123
from my render
method itself, wondering if that is possible?
@Component({ tag: 'my-ponent' })
export class MyComponent {
render() {
return (
<div><slot /></div>
)
}
}
I would like to do some string formatting on 123
instead of rendering slot
directly
- An alternative would be to have it as a property instead. – Thomas Commented Oct 14, 2020 at 13:39
- @Thomas: Yup of course, but that would not be ideal – Isaac Commented Oct 15, 2020 at 1:25
2 Answers
Reset to default 3In web ponents, the content inside of it is part of the main DOM, too. This content is not going to show if you don't use slots; but, the content is going to project next to the #shadow-root anyway (check it using the chrome developer tools in the "elements" section).
So, if you do not want to show the content using default slots, you can use the property decorator @Element()
and declare a property of type HTMLElement:
Then, you can access to the content via innerHTML
or innerText
.
Finally, you can format the content. Check the code snippet bellow:
import { Component, Element, h } from "@stencil/core";
@Component({
tag: 'my-ponent',
styleUrl: 'my-ponent.css',
shadow: true
})
export class MyComponent {
@Element() element: HTMLElement;
formatContent(content: any) {
if ( isNaN(content)){
// Your format here
return content;
} else {
return content + '.00';
}
}
render() {
return [
// Commented slot tag
// <slot></slot>,
<div> {this.formatContent(this.element.innerHTML)} </div>
];
}
}
Using three times the web ponent with 2 strings and a number as a entry data, the result should be:
My text
My text 2
123.00
import { Element } from '@stencil/core';
@Component({ tag: 'my-ponent' })
export class MyComponent {
/**
* Reference to host element
*/
@Element() host: HTMLElement;
ponentWillRender() {
console.log(this.host.innerHTML)
}
render() {
return (
<div><slot /></div>
)
}
}