【问题标题】:Adjust height of dropdown menu Angular7 autocomplete with virtual-scroll使用虚拟滚动调整下拉菜单Angular7自动完成的高度
【发布时间】:2019-04-04 16:19:22
【问题描述】:

我正在为我的应用程序使用 angular-material Autocomplete(版本 7)。我在里面使用<cdk-virtual-scroll-viewport>。除了我解决的许多问题,还有一个我不明白:

当我添加 max-height css 时下拉菜单不显示,如果我添加高度,它会显示但高度固定。

这是我的部分代码: html:

<mat-form-field class="single-select">
  <input matInput #singleInput class="single-input layout flex" type="text" [formControl]="selectControl" [matAutocomplete]="auto" (blur)="onBlur()" (focus)="onFocus()">

  <mat-autocomplete class="single-autocomplete" #auto="matAutocomplete" [displayWith]="displayFn">
    <cdk-virtual-scroll-viewport itemSize="45" minBufferPx="360" maxBufferPx="360" class="virtual-scroll">
      <mat-option *cdkVirtualFor="let option of filteredOptions" [class.selected]="option === oldValue" [value]="option" (click)="onSelect(option)">{{option.label}}</mat-option>
    </cdk-virtual-scroll-viewport>
  </mat-autocomplete>
</mat-form-field>

ts:

export class SingleSelectComponent implements OnInit {
  @Input() value;
  @Input('options')
  set options(value) {
    if (value) {
      this.filteredOptions = value.slice();
      this.data = value;
      this.initValue();
    }
  }
  @Output() formValue = new EventEmitter<any>();

  @ViewChild('singleInput') singleInput;

  selectControl = new FormControl('');
  filteredOptions;
  oldValue: any;
  data: any;
  destroy: Subject<boolean> = new Subject<boolean>();

  constructor(private appService: AppService,
              private translationService: TranslationService) { }

  ngOnInit() { this.selectControl.valueChanges.pipe(takeUntil(this.destroy)).subscribe((value)=>{
      let valStr = typeof value === 'string' ? value : value.label;

      this.filteredOptions = valStr ? this.filter(valStr) : this.data.slice();
      this.value = this.selectControl.value;
      if(typeof value !== 'string' || value === '') this.formValue.emit(value);
    });
  }

  ngOnDestroy() {
    this.destroy.next(true);
    this.destroy.unsubscribe();
  }

  private filter(name: string) {
    return this.data.filter(option => this.normalizeInput(option.label).indexOf(this.normalizeInput(name)) >= 0);
  }

  private normalizeInput(value: string) {
    return value.normalize('NFD').replace(/[\u0300-\u036f]/g, "").toLowerCase();
  }

  initValue() {
    let value = this.data.find(option => option.code === this.value.code);

    this.selectControl.setValue(value ? value : '');
    this.filteredOptions = this.filter(value ? value.label : '');
    this.oldValue = value;
  }

  displayFn(option) {
    return option ? option['label'] : '';
  }

  onSelect(option) {
    this.oldValue = option;
    this.singleInput.nativeElement.blur();
  }

  onBlur() {
    if(this.selectControl.value) {
      let found = this.data.find(option => this.selectControl.value.code === option.code);

      if(!found) {
        setTimeout(()=> {
          this.selectControl.setValue(this.oldValue);
          this.filter(this.oldValue.label);
        }, 200);
      } else {
        this.filter(this.oldValue.label);
      }
    } else {
      this.oldValue = null;
      this.filteredOptions = this.data;
    }
  }

  onFocus() {
    let virtualScrollEl = document.body.getElementsByClassName('virtual-scroll')[0];
    if(virtualScrollEl) {
      virtualScrollEl.scrollTo(0, 0);
    }
  }
}

css:

.single-input {
    height: 100%;
    min-width: 20%;
    max-width: 100%;
}

.virtual-scroll {
    height: 350px;
    overflow-x: hidden;
}

mat-option {
    height: 45px;
    font-size: 13px;
}

::ng-deep .mat-autocomplete-panel.single-autocomplete {
    max-height: 350px;
}

.virtual-scroll ::ng-deep .cdk-virtual-scroll-orientation-vertical .cdk-virtual-scroll-content-wrapper {
    width: 100%;
}

在虚拟滚动类中,我必须添加一个固定高度。当项目的高度小于 350px 时,会创建一个空白区域。

这是小提琴:https://stackblitz.com/edit/angular-fs4voi。由于我对 Angular 完全陌生,并且我对自动完成进行了一些修改,因此也可能导致此问题。

非常感谢!

【问题讨论】:

    标签: angular autocomplete virtualscroll angular-material-7


    【解决方案1】:

    您可以使用mat-autocomplete 上的class 选项来指定下拉面板的样式。因为面板在叠加层中,所以该类需要采用您的全局样式。而对于max-height,因为mat-autocomplete 也定义了它,所以需要!important 覆盖。那么你根本不需要实现自己的虚拟滚动。

    组件:

    <mat-autocomplete class="single-autocomplete" #auto="matAutocomplete" [displayWith]="displayFn">
        <mat-option *ngFor="let option of filteredOptions" [class.selected]="option === oldValue" [value]="option" (click)="onSelect(option)">{{option.label}}</mat-option>
    </mat-autocomplete>
    

    全局样式.css

    .single-autocomplete {
        max-height: 350px !important;
    }
    

    https://stackblitz.com/edit/angular-jngfv7?embed=1&file=src/styles.css

    【讨论】:

    • 非常感谢您的帮助!
    • 对不起,我取消了最佳答案,因为我真的想要带有自动完成功能的虚拟滚动,而不是 mat-option。有什么想法吗?非常感谢
    • 非常棘手 - 不确定是否可以完成。 CdkVirtualScroll 似乎意味着它总是有一个固定的高度。您可以尝试将[style.height] 绑定到执行某种计算的函数,但您需要知道列表中有多少“项目”,这当然是动态的,因此这两个原则对每个都有效其他。
    • 是的,我同意。使虚拟滚动的自动高度似乎不是一个正确的概念。我将对少量元素使用 md-options,对大量元素使用 virtual-scroll。再次感谢您的帮助。
    • 有一个更好的方法可以做到这一点,而不必使用!important:将它嵌套在它的父样式下,所以你的选择器获得更高的优先级,它会覆盖默认值而不使用!important
    【解决方案2】:

    您可以使用 [style.height] 并在函数中计算高度:

    HTML:

    <mat-autocomplete #autoPolicy="matAutocomplete" [panelWidth]="'450px'" >
                  <cdk-virtual-scroll-viewport itemSize="20" [style.height]="caclVSHeight()">
                    <mat-option *cdkVirtualFor="let policy of filteredPolicies | async" [value]="policy.name">
                      <span style="font-size: smaller;">{{ policy.name }}</span>
                    </mat-option>
                  </cdk-virtual-scroll-viewport>
    
                </mat-autocomplete>
    

    TS:

    virtScrollLength: number;
    filteredPolicies: Observable<any[]>;
    
    ngOnInit() {
      this.filteredPolicies = this.fcPolicy.valueChanges
        .pipe(
          startWith(''),
          map(value => this._filterPolicy(value))
        );
    }
    
      private _filterPolicy(value: string): any[] {
        if (value) {
          const filterValue = value.toLowerCase();
          const arr = this.policies.filter(pol => pol.name.toLowerCase().includes(filterValue))
          this.virtScrollLength = arr.length;
          return arr;
        } else {
          return this.policies;
        }
      }
    
    caclVSHeight() {
        if (this.virtScrollLength > 10) {
          return '240px';
        } else {
          return '120px';
        }
      }
    

    【讨论】:

      猜你喜欢
      • 2021-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-06
      • 2018-04-27
      相关资源
      最近更新 更多