ngx-bootstrap Закрытие аккордеона при подписке на метод API

У меня есть аккордеон ngx-bootstrap, который закрывает открытую панель каждый раз, когда я вызываю данные из API, используя .subscribe()метод. Все содержимое заголовков аккордеона изменяется плавно, без видимой перезагрузки, но, поскольку изменение содержимого внутри аккордеона управляется ползунком диапазона, очень раздражает необходимость повторно открывать панель каждый раз, когда ползунок ярости изменяется..

Как я могу предотвратить это?

HTML:

<accordion [isAnimated]="true" [closeOthers]="true">
    <accordion-group *ngFor="let r of reccs; let i = index" panelClass="customClass">
        <div class="row text-left" accordion-heading>
            <div class="col">
                <h4><strong [ngStyle]="{'color': brand?.colours.primary}">{{ r.name }}</strong> <small [ngStyle]="{'color': brand?.colours.secondary}"> {{ r.financials.representativeAmountAsString }} {{termTimeDisplay}}</small> <span *ngIf="i===0" class="badge badge-success ml-3">Recommended</span></h4>
                <p [ngStyle]="{'color': brand?.colours.tertiary}">{{ r.tagline }}</p>
            </div>
            <div class="col">
                <div id="progress" class="container">
                    <div class="hex-container">
                        <div *ngFor="let p of r.products" [popover]="popTemplate" [popoverTitle]="p.type" triggers="mouseenter:mouseleave" [ngClass]="{'product-included': p.inclusivity === 'included', 'product-not-required' : p.inclusivity === 'notRelevant'}">
                            <ng-template #popTemplate>{{p.name}}</ng-template>
                            <img src="../../assets/questions/progress/1.png" >
                        </div>
                    </div>
                  </div>
                </div>
              </div>
              <div class="row mt-3">
                <div class="col">
                  <p>{{ r.name }}</p>
                </div>
              </div>
            </accordion-group>
          </accordion>

Вызов метода API:

loadRecommendations(term: number, paymentCycle: string) {
    // Get the choices from the API
    this.reccommendationsService.getRecommendations(term, paymentCycle).subscribe(res => {
      // Load the choices to angular
      this.choices = res;
      // Initalise the reccommendations array
      this.reccs = new Array();
      // Load the array with choices
      for (const c of this.choices.choices) {
        // Make a stringly typed choice model
        this.recc = c;
        // Add choice model to the array
        this.reccs.push(this.recc);
      }
      this.reccs.reverse();
      if (this.reccs) {
        this.chiocesPresent = true;
        this.bestProduct = this.reccs[0];
      } else {
        this.chiocesPresent = false;
      }
      this.allInclusive();
      this.allInclusiveFeatures();
    });
  } 

Слайдер:

<div class="text-center sliders">
        <input type="range" min="6" max="60" step="6" class="slider" [(ngModel)]="term" id="term" (change)="loadRecommendations(this.term, this.termTime)">
        <p class="text-right mt-2">{{term}} months</p>
      </div>

1 ответ

Решение

Это обычная проблема при работе с Angular. Ваш контент обновляется, поэтому у Angular нет другого выбора, кроме как уничтожить его из dom и создать его снова, теряя отслеживание элемента.. Надеюсь, решения существуют!

Я бы посоветовал вам использовать trackByFn https://netbasal.com/angular-2-improve-performance-with-trackby-cc147b5104e5

Этот ответ также очень хорошо объясняет, что он делает и как его использовать /questions/18611783/kak-ispolzovat-trackby-s-ngfor/18611794#18611794

Другие вопросы по тегам