最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get text content of slot? - Stack Overflow

programmeradmin3浏览0评论

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

Share Improve this question edited Oct 12, 2020 at 3:39 Isaac asked Oct 12, 2020 at 3:32 IsaacIsaac 12.9k18 gold badges64 silver badges134 bronze badges 2
  • 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
Add a ment  | 

2 Answers 2

Reset to default 3

In 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>
    )
  }
}

发布评论

评论列表(0)

  1. 暂无评论