github / catalyst

Catalyst is a set of patterns and techniques for developing components within a complex application.
https://github.github.io/catalyst/
MIT License
1.34k stars 50 forks source link

How can I render html both in component element and out component element? #294

Closed qlfy17 closed 1 year ago

qlfy17 commented 1 year ago

First,define the primary-button component,like this:

@controller
class PrimaryButtonElement extends HTMLElement {
  connectedCallback(){
       const itemTemplate = () => {
           return html`
          <button>
              ???
          </button>
          `
        }

        render(itemTemplate(), this)
   }
}

Then,use the component like this,

<primary-button>new issue</primary-button>

The question is how to render the component's content in the controller? Thanks!

Scipion commented 1 year ago

I'm not sure of the question. Do you mean you want to wrap what the children of the tag into your button? if so you can get the initial content with this.innerHTML as a string and do it like so:

@controller
export class PrimaryButtonElement extends HTMLElement {
  connectedCallback(){
        const initialContent = this.innerHTML;
        const itemTemplate = (content:string) => {
           return html`<button>${content}???</button>`
        }

        this.innerHTML=''
        render(itemTemplate(initialContent), this);
   }
}

You will have to get rid of it and re-render it again. it will render:

<primary-button data-catalyst="">
    <button>new issue???</button>
</primary-button>

I hope it helps.

qlfy17 commented 1 year ago

I'm not sure of the question. Do you mean you want to wrap what the children of the tag into your button? if so you can get the initial content with this.innerHTML as a string and do it like so:

@controller
export class PrimaryButtonElement extends HTMLElement {
  connectedCallback(){
        const initialContent = this.innerHTML;
        const itemTemplate = (content:string) => {
           return html`<button>${content}???</button>`
        }

        this.innerHTML=''
        render(itemTemplate(initialContent), this);
   }
}

You will have to get rid of it and re-render it again. it will render:

<primary-button data-catalyst="">
    <button>new issue???</button>
</primary-button>

I hope it helps.

thanks a lot