【问题标题】:bootstrap-select not updating dynamically in angular引导选择不以角度动态更新
【发布时间】: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 期间的选择中填充了一些初始数据,这可以正常工作。但是当我尝试通过更改模型来通过代码更新selectoptions 时,似乎没有反映。我注意到的一件事是,如果我删除了 appBootstrapSelect 属性,select 将具有默认样式,并且代码绑定可以工作,这是我想要的行为。

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 code 我认为需要调用它才能更新列表,但不确定如何在角度上做同样的事情。我确实有appBootstrapSelect 的模型参考

 @ViewChildren('appBootstrapSelect') motherCompanyDropdown: ElementRef;

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

PS:我也试过ChangeDetectionStrategy,但是不行。

【问题讨论】:

    标签: angular bootstrap-4 angular6


    【解决方案1】:

    `你好,

    由于您的指令中已经有了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');
      })
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-17
      • 1970-01-01
      • 2016-12-03
      相关资源
      最近更新 更多