Angular 2 - ng-bootstrap popup menu with formControlName

Is there a way to make ng-bootstrap drop down control work with Angular 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 formControlName be used in the same way as on inputs?

<input formControlName="name" />
+4
source share
2 answers

Unfortunately, the drop-down list ng-bootstrapcannot be used as a ready-made form control.

, . ControlValueAccessor. : https://blog.thoughtram.io/angular/2016/07/27/custom-form-controls-in-angular-2.html

+3

, , .

HTML:

<div class="btn-group dropdown">
    <input [id]="field.id" [formControlName]="field.id" type="text" disabled class="form-control dropdown-toggle">                                    
<ul class="dropdown-menu">
    <li class="active"><a class="dropdown-item" (click)="onDropdownSelect($event)">Action - 1</a></li>
    <li><a class="dropdown-item" (click)="onDropdownSelect($event)">Another action</a></li>
    <li><a class="dropdown-item" (click)="onDropdownSelect($event)">Something else here</a></li>
</ul>
<span role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" class="input-group-addon dropdown-toggle"><span class="caret"></span>
</span>
</div>

Angular :

onDropdownSelect(e) {        
// This is to remove 'active' class from all li tags
$(e.target.parentElement.parentElement).find('li.active').removeClass(Constants.common.activeCssClass);

// This is to make form dirty when value selected
(this.form.controls[e.target.parentElement.parentElement.previousElementSibling.id] as FormControl).markAsDirty();

// This is to set selected value in textbox to update form in DOM
 $(e.target.parentElement.parentElement.previousElementSibling).val($(e.target).text());

// This is to set css class to show value as selected
$(e.target.parentElement).addClass(Constants.common.activeCssClass);        
}

:   ,

console.log(this.form.value);
{"id": "Action - 1"}

, .

0

Source: https://habr.com/ru/post/1669070/


All Articles