Is it possible to bind the Polymer paper-dropdown-menu with ngControl in Angular?

I'm currently working on building a form in Angular2 using the Polymer paper-dropdown-menu element. I've been struggling to figure out how to bind the selected value of the dropdown to my component's control. Despite numerous attempts, I haven't had any success. Has anyone managed to overcome this challenge?

Here is an example of a functional paper-input:

template:

<paper-input type="password"
             ngControl="password"
             ngDefaultControl>
</paper-input>

component:

constructor(private fb:FormBuilder) {

    this.loginForm = fb.group({
        password: new Control("")
    });
}

Is there a similar approach for paper-dropdown-menu? I would be satisfied with either binding to the value or the text itself. Thank you!

Answer №1

To achieve the desired functionality, a custom ControlValueAccessor is necessary. While using a ControlValueAccessor directly for the paper-dropdown-menu may not work as expected, implementing it for the paper-menu or paper-listbox inside the paper-dropdown-menu can be successful.

const PAPER_MENU_VALUE_ACCESSOR = new Provider(
    NG_VALUE_ACCESSOR, {useExisting: forwardRef(() => PaperMenuControlValueAccessor), multi: true});


@Directive({
  selector: 'paper-listbox',
  host: {'(iron-activate)': 'onChange($event.detail.selected)'},
  providers: [PAPER_MENU_VALUE_ACCESSOR]

})  
export class PaperMenuControlValueAccessor implements ControlValueAccessor {
  onChange = (_:any) => {
  };
  onTouched = () => {
  };

  constructor(private _renderer:Renderer, private _elementRef:ElementRef) {
    console.log('PaperMenuControlValueAccessor');
  }

  writeValue(value:any):void {
    //console.log('writeValue', value);
    this._renderer.setElementProperty(this._elementRef.nativeElement, 'selected', value);
  }

  registerOnChange(fn:(_:any) => {}):void {
    this.onChange = fn;
  }

  registerOnTouched(fn:() => {}):void {
    this.onTouched = fn;
  }
}

For more information, refer to:

  • ngModel Binding on Polymer dropdown (Angular2)
  • Bind angular 2 model to polymer dropdown

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When deciding where to subscribe - in the service or the component - in Angular, it is important to consider the

Many developers often debate whether it is better to subscribe from a service or a component: Angular 2: Should you subscribe from a component or a service? advises against manually subscribing from a component. If we don't require any data, why do ...

What is the process for publishing TypeScript interface definitions via npm?

I've been grappling with this problem for the past few days, scouring the internet and reading extensively, but I haven't come across any examples that match my specific scenario. My goal is to publish a library using npm that includes its own ty ...

The 'Element[]' type is lacking certain properties when dealing with react children

In my code, there is a parent component passing down its children to a child component. These children can be either single nodes or arrays of nodes, and the ChildComponent renders them differently based on their type. However, when I try to render the Chi ...

Maintaining the order of the returned values type is crucial when working with mapped objects in Typescript

Currently, I am developing a basic mapper function for objects. This function is designed to take an array of object properties and then return an array containing the corresponding values of these properties. The function works as intended; however, I hav ...

Angular 11.0.3 displaying ngClass issue (Unable to bind ngClass as it is not recognized as a property of div)

While working on an angular project, I implemented a light and dark theme using mat-slide-toggle to switch between themes. The theme is stored as a boolean called isDark in a Behavioral Subject service. There are two lazy-loaded modules - one for the home ...

The close button in Angular 4 is unresponsive until the data finishes loading in the pop-up or table

Having trouble with the Close button in Angular 4 popup/table The Pop Up is not closing after clicking anywhere on the screen. I have added backdrop functionality so that the pop-up closes only when the user clicks on the close icon. However, the close i ...

Creating a numeric sequence based on the date of a corresponding transaction - a step-by-step guide

INTRO I built an e-commerce app with TypeScript and Sequelize ORM. In the app, I have a table that generates sequential invoice numbers based on the current day. CREATE TABLE `dm_generate_trx` ( `id` int NOT NULL AUTO_INCREMENT, `date` date NOT NULL, ...

Step-by-step guide for installing @ng-select when upgrading to Angular 10

There seems to be an issue with the package "@ng-select/ng-select" that is causing compatibility errors. I encountered this error while trying to update from Angular 8 to Angular 10. Check out the screenshot for more details: click here ...

Challenge encountered with asynchronous angular queries

Dealing with asynchronous calls in Angular can be tricky. One common issue is getting an array as undefined due to the asynchronous nature of the calls. How can this be solved? private fetchData(id){ var array = []; this.httpClient.get('someUrl ...

Hide the tab in React Native's bottom tab navigation when on the current screen within the navigator

Currently, I am delving into learning react native. My project consists of 4 screens, yet I only require 3 buttons on my tab navigator. The objective is to hide or eliminate the active screen's tab from being accessible. Specifically, when on the home ...

I've noticed that the list item vanishes unexpectedly when utilizing Primeng drag-and-drop feature

Whenever I try to drag an item from one list to another in the Primeng picklist, the item disappears until it is dropped. <p-dialog [(visible)]="showMarker" (onHide)="hideDialogChild()" [contentStyle]="{'overflow':'visible'}" h ...

Tips for preventing automatic login when a new user is added in firebase

I am looking to enable users to create additional accounts, however, I encountered an issue when using createUserWithEmailAndPassword which automatically signs in the new user. How can I prevent this from happening? My goal is to set up a user account fro ...

The best method for obtaining a reference to the Angular/Google Maps component in your code

Currently, I am using @angular/google-maps": "^17.3.5" and angular "^17.3.5". I am attempting to obtain a reference to my google-map element in my component. <google-map #map mapId="map" height="100%" width="100%" [options]="options"</google-map&g ...

Having trouble getting the NextJS custom 404 page to display?

I've located the 404.tsx file in the apps/specificapp/pages/ directory, yet NextJS continues to show the default pre-generated 404 page. Could there be a misunderstanding on my part regarding the documentation, or is there some obstacle preventing me ...

Exploring the concept of object inheritance in Angular 5 with Typescript

I'm facing a challenge related to inheritance while building my initial angular 5 application. The error message I encounter is: Property 'message' does not exist on type 'CouponEvent', as reported by the angular-cli. export class ...

Unable to submit a post on Ionic 3 platform

I've been attempting to make a POST request using HttpClient Angular to communicate with a server, but I've encountered an error in my code: File: *.ts import { HttpClient } from '@angular/common/http'; constructor(public http: Http ...

Implementing Autocomplete feature in Reactjs with Ant Design Library

In my React application, I created an autocomplete feature with a list of options for the user to select from. Example in Action: Click here to see the demo List of available options: const options = [ { label: "hello", value: "1" ...

Why did my compilation process fail to include the style files despite compiling all other files successfully?

As English is not my first language, I kindly ask for your understanding with any typing mistakes. I have created a workspace with the image depicted here; Afterwards, I executed "tsc -p ." to compile my files; You can view the generated files here Unf ...

How come accessing the superclass's property with a getter in TypeScript is not working as expected?

class A { protected _value:number; get value() { return this._value; } } class B extends A { set value(v:number) { this._value = v; } } var b = new B(); b.value = 2; console.log(b.value);//undefined Coding Pla ...

Angular: Utilizing httpClient to retrieve an object map and passing it as a return value in a function

I have a basic Angular application that retrieves data from a Spring-Boot backend. export class UserDto { constructor( public login: string, public password: string, ) { } } export class AuthService { private url = '....'; get ...