2

I am trying to create a form in Angular2 using the Polymer paper-dropdown-menu control. Is there a way to bind the selected value of the dropdown to the control in my component? I have tried everything with no luck. Has anyone gotten over this hurdle?

An example of a working paper-input is:

template:

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

component:

constructor(private fb:FormBuilder) {

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

Is there something similar for paper-dropdown-menu? Either binding to the value or the text itself would be fine. Thanks!

Sloth Armstrong
  • 1,066
  • 2
  • 19
  • 39

1 Answers1

1

You need a custom ControlValueAccessor. I didn't succeed using a ControlValueAccessor for the paper-dropdown-menu itself but for the paper-menu or paper-listbox inside the paper-dropdown-menu like

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;
  }
}

See also

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567