Search code examples
javascriptpolymerweb-componentpolymer-2.x

Accessing properties from a function in Web Components


I am converting a project from Angular to Web Components / Custom Elements and am trying to replace ng-model by creating a binding for the following text field:

<input type="search" class="form-control search_input" placeholder="Search for someone new" value$="[[userLookup:input]]" required autocomplete="off">

Obviously since this is converted from Angular, I need to be able to access this value in a JavaScript function:

(function(customElements) {
    class RecentSearch extends PolymerMixins.LightDomMixin(Polymer.Element) {
        static get is() { return 'recent-search'; }

        static get properties() {
            return {
                properties: {
                    user: {
                        type: Object
                    },
                    userLookup: {
                        type: String,
                        reflectToAttribute: true,
                        value: '',
                    },
                },
            };
        }

        lookupUser() {
            if (this.userlookup) {
                $state.go('users', { query: userlookup });
            }
        };
    }
    customElements.define(RecentSearch.is, RecentSearch);
})(window.customElements);

How would I access the userLookup property (the one bound to the text field) from inside the lookupUser function?


Solution

  • You're already accessing userLookup correctly from lookupUser() with this.userLookup. The event handler's context (i.e., this) is the Polymer element instance.

    However, your data binding is incorrectly a one-way data binding, so userLookup would not be updated. This kind of binding needs to be two-way (i.e., with curly brackets) and cannot use attribute binding (i.e., $=).

    The correct usage should be something like this:

    <input placeholder="Search for someone new"
           value="{{userLookup::change}}" />
    

    demo