【发布时间】:2020-10-31 06:51:25
【问题描述】:
我的网页中有一个选择 (bootstrap-select),其中包含一些将根据某些过滤器更新的数据。数据通过 API 绑定到 select。
<select appBootstrapSelect data-live-search="true" [(ngModel)]="mCompany" >
<option value=''>All</option>
<option *ngFor="let motherCompany of motherCompanies " [ngValue]="motherCompany.id">
{{motherCompany.name}}
</option>
</select>
在ngOnInit 期间的选择中填充了一些初始数据,这可以正常工作。但是当我尝试通过更改模型来通过代码更新select 的options 时,似乎没有反映。我注意到的一件事是,如果我删除了 appBootstrapSelect 属性,select 将具有默认样式,并且代码绑定可以工作,这是我想要的行为。
appBootstrapSelect 是Directive,其代码如下
import { Directive, ElementRef, OnInit, OnDestroy } from '@angular/core';
declare var jQuery: any;
/**
* Directive to wrap bootstrap-select
*/
@Directive({
selector: '[appBootstrapSelect]'
})
export class BootstrapSelectDirective implements OnInit, OnDestroy {
private el;
constructor(private elref: ElementRef) {
this.el = elref.nativeElement;
}
ngOnInit() {
// wrapping in setTimeout to delay init until after attribute binding
setTimeout(() => {
jQuery(this.el).selectpicker({
iconBase: 'fa',
tickIcon: 'fa-check'
});
},2000);
}
ngOnDestroy() {
jQuery(this.el).selectpicker('destroy');
}
refresh() {
jQuery(this.el).selectpicker('refresh');
}
/**
* Manually dispatch a change event to let Angular know of a programmatic change to the select
*/
triggerChangeEvent() {
this.el.dispatchEvent(new Event('change', { 'bubbles': true }));
}
/**
* Select an option in this select by id
* @param id
*/
selectOptionById(id) {
jQuery(this.el).find('#'.concat(id)).prop('selected', true);
this.triggerChangeEvent();
}
}
我发现了一个jQuery code 我认为需要调用它才能更新列表,但不确定如何在角度上做同样的事情。我确实有appBootstrapSelect 的模型参考
@ViewChildren('appBootstrapSelect') motherCompanyDropdown: ElementRef;
为什么会发生这种情况?我该如何解决这个问题?
PS:我也试过ChangeDetectionStrategy,但是不行。
【问题讨论】:
标签: angular bootstrap-4 angular6