Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - ng-bootstrap dropdown with formControlName

Is there a way to make the ng-bootstrap dropdown control work with Angular's reactive forms?

Given:

<div ngbDropdown class="d-inline-block">
  <button class="btn btn-outline-primary" id="dropdownMenu1" ngbDropdownToggle>Toggle dropdown</button>
  <div class="dropdown-menu" aria-labelledby="dropdownMenu1">
    <button class="dropdown-item">Action - 1</button>
    <button class="dropdown-item">Another Action</button>
    <button class="dropdown-item">Something else is here</button>
  </div>
</div>

How can one use the formControlName much like used on inputs?

<input formControlName="name" />
like image 711
Thibs Avatar asked Feb 07 '17 19:02

Thibs


2 Answers

Unfortunately, ng-bootstrap dropdown can't be used as a form control out-of-the-box.

But it's possible to create your own component that will be used as a form control. To do it, you need to implement ControlValueAccessor interface. You can read more in this article: https://blog.thoughtram.io/angular/2016/07/27/custom-form-controls-in-angular-2.html

like image 50
Dmytro Yarmak Avatar answered Sep 28 '22 10:09

Dmytro Yarmak


I've made custom dropdown using ng-bootstrap and I'll give you description how I resolved it.

Change button for opening dropdown with input tag. Make it readonly and add action on click to open ngbDropdown (dropdown.open() in code example). For every item in the list add on click event to set formControl value.

Working example: https://stackblitz.com/edit/angular-46axva

like image 44
ZeroOrOne Avatar answered Sep 28 '22 10:09

ZeroOrOne