Search code examples
javascriptarraysweb-componentlit-element

how to make a method that push items to empty array with lit-element


I have an empty array with lit-element to add the ages between 2 to 13 years that I generate with a loop. I need to add each element within the array using a method but I don't know how to make it work. This is what I have:

import { LitElement, html } from 'lit-element';

class ChildrenInput extends LitElement {
    static get properties() {
        return {
            ages: {type: Array},
        };
    }

    constructor() {
        super();
        this.minAge = 2;
        this.maxAge = 13;
        this.ages = [];
    }

    ages() {
        for (let age = this.minAge; age <= this.maxAge; age++) {
            this.ages.push(age);
        }
    }

    render(){
        return html`
            <div>
                <select>
                    <option selected>--</option>
                    <option>${this.ages.map(item => html`<li>${item}</li>`)}</option>
                </select>
            </div>
        `;
    }
}

customElements.define('children-input', ChildrenInput);

Solution

  • You first need to call your function, having given a different name from the array property, and use the option element in the loop mechanism as follows:

    import { LitElement, html } from 'lit-element';
    
    class ChildrenInput extends LitElement {
        static get properties() {
            return {
                ages: {type: Array},
            };
        }
    
        constructor() {
            super();
            this.minAge = 2;
            this.maxAge = 13;
            this.ages = [];
            this.loopAges();
        }
    
        loopAges() {
            for (let age = this.minAge; age <= this.maxAge; age++) {
                this.ages.push(age);
            }
    
            // Alternative syntax:
            // let age = this.minAge; while ( age <= this.maxAge ) this.ages.push( age++ );
    
        }
    
        render(){
            return html`
                <div>
                    <select>
                        <option selected>--</option>
                        ${this.ages.map(item => html`<option value="${item}">${item}</option>`)}
                    </select>
                </div>
            `;
        }
    }
    
    customElements.define('children-input', ChildrenInput);
    

    Here's a working version