Установить выбранное значение в angular выпадающий не работает - PullRequest
0 голосов
/ 03 марта 2020

У меня есть выпадающее меню для фильтрации списка, в котором мне удается динамически восстановить параметры фильтра, но я не знаю, как заставить его фильтровать список и отображать только те из выбранных параметров.

Вот мой html:

  <div class="dropdown">
    <select-dropdown *ngIf="distinctYear" wrapperClass="input-mid" label="Filter by date" (eClickAction)="this.setDateSelected($event)" [options]="distinctYear"></select-dropdown>
  </div>

вот мой ts:

public distinctYear = [];

   getDistinctYear(bills) {
    if (bills) {     
      for (const bill of bills) {
        if (this.distinctYear.filter(value => {
          return value.value === bill['billing_at'].split('-')[0];
        }).length === 0) {
          this.distinctYear.push({title: bill['billing_at'].split('-')[0], value:  bill['billing_at'].split('-')[0]});
        }
      }
      this.distinctYear.push({title: 'All your bills', value: 'all'});
      return Array.from(new Set(this.distinctYear));
    }
  }

  setDateSelected(singleDate: any) {
    singleDate = singleDate;
    this.dateSelected.emit(singleDate);
    if (singleDate !== undefined && singleDate !== null) {
      this.bills.forEach((item: { disabled: boolean; billing_at: any; }) => {
        item.disabled = item.disabled !== singleDate;
      });
    if (singleDate === 'all') {
      this.bills.forEach((item: { disabled: boolean; billing_at: any; }) => {
        item.disabled = item.billing_at === singleDate;
      });
    }
    }
  }

есть 3-й компонент в качестве компонента выпадающего списка:

import { Component, EventEmitter, Input, OnInit, Output, HostBinding, HostListener } from '@angular/core';

@Component({
  selector: 'select-dropdown',
  templateUrl: './select-dropdown.component.html',
  styleUrls: ['./select-dropdown.component.scss']
})
export class SelectDropdownComponent implements OnInit {

  @Input() label = '';
  @Input() wrapperClass: string;
  @Input() options: any;
  @Input() defaultValue = null;
  @Input() search = false;
  @Input() extendSearchIn = [];
  @Input() stateSelected ;
  @Input() dateSelected ;
  @Input() resetConventions;
  @Output() output = new EventEmitter<string>();
  @Output() eClickAction = new EventEmitter<string>();


  private defaultValueStored = null;
  public toggle: boolean;
  public title: string;
  public disabled: boolean;
  private disabledString = 'disabled';
  private selectedObj: any;
  private _data = [];
  private classes: string[];

  @HostBinding('attr.tabindex') tabindex = '0';
  convention: any;

  @HostListener('blur', ['$event']) onBlur(e) {

    if (e.relatedTarget === null) {
      this.toggle = false;
      if (this.search) { this.changeSearch(''); }
    }

  }


  @Input()
  set data(value) {
    this._data = value;
    if (this._data !== undefined) {
      if (this.defaultValueStored !== null && this.defaultValueStored !== undefined && (this.defaultValueStored === this.defaultValue)) {
      //  this.setDefault();
      } else {
        this.resetControl();
      }
      this.setDisabledClass();
    }
  }

  get data() {
    return this._data;
  }


  constructor() {
    this.toggle = false;
    this.title = '';
  }

  ngOnInit() {

  }

  clickAction(option) {
    if ( option.value !== this.selectedObj) {
      this.selectedObj = option.value;
    }
      this.title = option.title;
      this.eClickAction.emit(option.value);
    }




  toggleSelect(e) {
    if (this.disabled || e.target.className === 'search') { return; }
    this.toggle = !this.toggle;
    if (this.search && !this.toggle) { this.changeSearch(''); }
  }


  resetControl() {
    this.clickAction({
      title: '',
      value: null
    });
  }

  setDisabledClass() {

    if (this.classes === undefined) { return; }
    if (this.data !== undefined && this.data.length) {

      this.disabled = false;
      this.classes = this.classes.filter(function(e) { return e !== this.disabledString; }, this);
    } else {
      this.disabled = true;
      this.classes.push(this.disabledString);
    }

    this.wrapperClass = this.classes.join(' ');
    this.toggle = false;

    if (this.defaultValueStored === null) {
      this.resetControl();
    }

  }

//   setDefault() {

//     if (
//           this.defaultValueStored === null ||
//           this.defaultValueStored === undefined ||
//           this.defaultValueStored === '' ||
//           this.data === null ||
//           this.data === undefined
//     ) {
//       return;
//     }

//     if (!this.data.length) {
//       this.setSelected({
//         title: '',
//         value: null
//       });
//       return;
//     }

//   const selected = this.data.find(item => {
//     return item.value === this.defaultValueStored || item.title === this.defaultValueStored;
//   });

//   this.setSelected({
//     title: (selected !== undefined) ? selected.title : '',
//     value: (selected !== undefined) ? selected.value : null
//   });

// }

  changeSearch(searchTerm: string) {

    this.data.forEach(item => {
      item.show = false;
      this.extendSearchIn.forEach(prop => {
        item.show = item.show || this.searchByProperty(item, prop, searchTerm);
      });
    });

  }

  searchByProperty(item: object, property: string, searchTerm: string) {
    return (<String>item[property].toLowerCase()).startsWith(searchTerm.toLowerCase());
  }
}


Я управляю чтобы показать все параметры фильтрации в комбо. И делая проверки в консоли, он устанавливает выбранное значение, но не фильтрует в списке. если кто-нибудь может дать мне руку. Заранее спасибо.

1 Ответ

1 голос
/ 03 марта 2020

Что такое селектор «выпадающий список», на который здесь ссылаются? Это сторонний компонент или ваш собственный компонент? Мог бы посоветовать лучше, если бы это было понятно.

Несмотря на это, обычно в самих выпадающих меню вы можете применять директиву * ngIf, но ваш html не перечисляет эти параметры. С заданным вами синтаксисом вы в основном применяете условие ко всему элементу управления.

Если у вас есть собственный компонент, вы можете добавить * ngIf к параметрам в этом элементе управления.

Другой подход заключается в фильтрации параметров в component.ts и передаче этих отфильтрованных параметров компоненту (т.е. нет необходимости в директиве * ngIf)

...