Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

375
Visualizações
How can I conditionally render LitElement with TypeScript?

So I am mapping through an array of objects and looking to display on the page when a radio button is selected. For example, if there are two objects in the array, there will be two radio buttons. If you press radio1, it should render form1. If you press radio2, it should hide form1 and show form2.

I created a property called formIndex to keep track of which button is being pressed so that I know which form to call but I'm having trouble implementing.

Current behavior: on page load, both radios appear with no data rendered yet. When I press radio1, it displays both form1 and form2. When I press radio2, it also displays both form1 and form2.

I'm using LitElement in a TypeScript file.

Here is the property I created. Since I'm mapping through an array starting at 0, I initialized this property to -1:

@state()
formIndex: number = -1;

Here is where I am rendering the forms:

protected renderMultipleForms(formConfig: any): TemplateResult {
        return html`
            ${formConfig?.formHeading ? html`<h3>${formConfig.formHeading}</h3>` : ''}
                ${formConfig.forms?.map((data: any) => html`
                    <!-- <adc-radio-group>
                        <adc-radio-button id="radioBtn" label=${data.label} @click="${this.handleClick}"></adc-radio-button>
                    </adc-radio-group> -->
                    <!-- RADIOS  -->
                    <input type="radio" id=${data.label} name="paymentRadios" @click="${this.handleClick}">${data.label} <br />
                    <!-- RENDERING FORMS  -->
                    <p id=${this.formIndex}>${this.formIndex > -1 ? this.renderForm(data.form, data.paymentIcons) : ''}</p>
                `)}
        `;
    }

Finally, here is the method to handle the clicking of the radios:

protected handleClick(e: any){
        if(e.target.id == this._data.forms[0].label){
            this.formIndex = 0
        } else if(e.target.id == this._data.forms[1].label) {
            this.formIndex = 1
        }
        console.log(this.formIndex);
    }

How can I make it to where only the first form is displayed when the first radio is clicked and only the second form is displayed when the second radio is clicked? Thanks!

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I would just use conditional rendering as described on the lit.dev docs

A minimal example looks like this:

@customElement('test-cond-render')
export class CondRender extends LitElement {
    
    @state()
    selectedForm = -1;

    formData = [
        {id: 0, title: 'form one'},
        {id: 1, title: 'form two'}
    ];


    renderForm() {
        if(this.selectedForm === -1) {
            return html`
                <span>Please select a form</span>
            `;
        } else if (this.selectedForm === 0) {
            return html`
                <form action="#" target="_blank">
                    <p>
                        Select your interests:<br>
                        <input type="checkbox" name="movies"> Movies<br>
                        <input type="checkbox" name="sports"> Sports<br>
                        <input type="checkbox" name="videogames"> Videogames
                    </p>
                    <input type="submit" value="Send data">
                </form>
            `;

        } else if (this.selectedForm === 1) {
            return html`
                <form action="#" target="_blank">
                <p>
                    Enter your full name: <input type="text" name="fullname">
                    <input type="submit" value="Send data">
                </p>
                </form>
            `;

        } else {
            return html`
                <span>Something went wrong..</span>
            `;
        }
    }
    handleClick(form_id:number) {
        console.log('handle click:', form_id);
        this.selectedForm = form_id;
    }
    render() {
        return html `
            <h2>Cond render</h2>
            ${this.formData.map((data) => 
                html`
                    <input type="radio" name="form-group" value="${data.id}" id="${data.id}" @click="${this.handleClick.bind(this, data.id)}">
                    <label for="${data.id}">${data.title}</label>
                `
            )}
            
            <div>${this.renderForm()}</div>
        `;
    }
}

Your forms might be more complicated but the principle should be the same.

You can also use the cache directive for the render so it won't re-create the DOM for the selected form every time it is switched.

<div>${cache(this.renderForm())}</div>
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda