Así que estoy mapeando a través de una matriz de objetos y buscando mostrar en la página cuando se selecciona un botón de opción. Por ejemplo, si hay dos objetos en la matriz, habrá dos botones de radio. Si presiona radio1, debería representar form1. Si presiona radio2, debería ocultar form1 y mostrar form2.
Creé una propiedad llamada formIndex para realizar un seguimiento de qué botón se presiona para saber a qué formulario llamar, pero tengo problemas para implementar.
Comportamiento actual: en la carga de la página, ambas radios aparecen sin datos renderizados todavía. Cuando presiono radio1, muestra form1 y form2. Cuando presiono radio2, también muestra form1 y form2.
Estoy usando LitElement en un archivo TypeScript.
Aquí está la propiedad que creé. Como estoy mapeando a través de una matriz que comienza en 0, inicialicé esta propiedad en -1:
@state() formIndex: number = -1;
Aquí es donde estoy renderizando los formularios:
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> `)} `; }
Finalmente, aquí está el método para manejar el clic de las 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); }
¿Cómo puedo llegar a donde solo se muestra el primer formulario cuando se hace clic en la primera radio y solo se muestra el segundo formulario cuando se hace clic en la segunda radio? ¡Gracias!
Simplemente usaría la representación condicional como se describe en los documentos lit.dev
Un ejemplo mínimo se ve así:
@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> `; } }
Sus formularios pueden ser más complicados, pero el principio debería ser el mismo.
También puede usar la directiva de caché para el procesamiento para que no vuelva a crear el DOM para el formulario seleccionado cada vez que se cambia.
<div>${cache(this.renderForm())}</div>