如何在angular2应用程序中的Bootstrap Drop Down中使用反应形式

时间:2017-08-17 18:18:57

标签: angular angular2-forms

import { BsDropdownModule } from 'ngx-bootstrap/dropdown';
// or
import { BsDropdownModule } from 'ngx-bootstrap';

@NgModule({
  imports: [BsDropdownModule.forRoot(),...]
})
export class AppModule(){}

<div class="btn-group" dropdown>
  <button dropdownToggle type="button" class="btn btn-primary dropdown-toggle">
    Button dropdown <span class="caret"></span>
  </button>
  <ul *dropdownMenu class="dropdown-menu" role="menu">
    <li role="menuitem"><a class="dropdown-item" href="#">Action</a></li>
    <li role="menuitem"><a class="dropdown-item" href="#">Another action</a></li>
    <li role="menuitem"><a class="dropdown-item" href="#">Something else here</a></li>
    <li class="divider dropdown-divider"></li>
    <li role="menuitem"><a class="dropdown-item" href="#">Separated link</a>
    </li>
  </ul>
</div>

我应该在上面的代码中使用formControlName?对于模板表单,它非常简单。但是在Reactive中,如果它不是输入,我怎样才能获得更新的模型值?

1 个答案:

答案 0 :(得分:0)

您可以像下面的代码那样按照您的要求进行少量操作。

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</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>
    <li></li>
    <li><a class="dropdown-item" (click)="onDropdownSelect($event)">Separated link</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>

角度组件:

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

我希望,这可以帮助您解决问题。