引导程序选择不按角度动态更新



我的网页中有一个select(bootstrap select(,它由一些数据组成,这些数据将根据一些过滤器进行更新。数据通过API绑定到选择。

<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中,这很好。但当我试图通过更改模型来通过代码更新selectoptions时,它似乎没有反映出来。我注意到的一件事是,如果我删除了属性appBootstrapSelectselect将具有默认样式,并且绑定来自代码工作,这就是我想要的行为。

appBootstrapSelectDirective,其代码如下

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代码,我认为需要调用它才能更新列表,但不确定如何在angular中执行同样的操作。我确实有appBootstrapSelect的型号参考

@ViewChildren('appBootstrapSelect') motherCompanyDropdown: ElementRef;

为什么会发生这种情况?我该如何解决这个问题?

附言:我也试过ChangeDetectionStrategy,但不起作用。

`你好,

由于您的指令中已经有了refresh方法,所以您所需要做的就是在更新选项数据时调用它。要从组件调用它,您需要使用ViewChild,如下所示:

您的组件.ts

@ViewChild(BootstrapSelectDirective) motherCompanyDropdown: BootstrapSelectDirective;
//...
update() {
// new data
this.motherCompanies = [...];
// call refresh
this.motherCompanyDropdown.refresh();
}

但由于您使用了setTimeout,如果不在refresh方法中添加setTimeout可能无法工作:

你的方向.ts

refresh() {
setTimeout(() => {
jQuery(this.el).selectpicker('refresh');
})
}

最新更新