当自动完成隐藏在滚动区域中时,Angular Material自动完成面板不会隐藏

在此处输入图片说明

我为此打开了一个错误(https://github.com/angular/components/issues/20209),我在问这个问题,看看是否有解决方法或任何人都知道的修复方法。

该问题在此演示页面上可见https://stackblitz.com/edit/angular-rczreu

The issue is due to the CDK panel (autocomplete's panel) being rendered as a separate layer in the demo, distinct from the autocomplete element. So when the autocomplete element moves out of the visible area of the scrollable element, the autocomplete does become hidden, but the panel does not due to this separate layer rendering.

In pseudo code, the angular html is as follows,

<html>
<body>
<my-app>

<my-component cdkScrollable> // this is a scrollable element, it's children should become hidden when we scroll

<autocomplete></autocomplete>
<some-other-child></some-other-child>

</my-component>

</my-app>

<div class="cdk-overlay-container">
  // ... other stuff

  <div>
    // autocomplete's panel 
  </div>
</div>

Raven

Okay, I've made a fork of your StackBlitz with the solution here: https://stackblitz.com/edit/angular-rczreu-yqyphm

Basically here are the highlights:

On your component html, I added a component ID to the formField:

<mat-form-field #formField class="example-full-width">

Then on your component ts, I added the references to the ViewChild for the Autocomplete elements (the form field and the Autocomplete panel itself):

@ViewChild(MatAutocompleteTrigger) autocomplete: MatAutocompleteTrigger;
@ViewChild("formField") autoCompleteFormField: MatFormField;

然后,我将AfterViewInit的实现添加到您的组件中,以确保视图元素已经加载,因此它不是未定义的。

ngAfterViewInit() {
    var observer = new IntersectionObserver((entries) => {
      if(!entries[0].isIntersecting)
        console.log('Element is is not in screen');
        this.autocomplete.closePanel();
    }, { threshold: [1] });

    
 observer.observe(this.autoCompleteFormField._elementRef.nativeElement);
}

因此,此代码段使用的是高效的Intersection Observer API,它可以检测元素是否在屏幕上。然后,如果元素不在屏幕上,则只需关闭自动完成面板。

https://usefulangle.com/post/113/javascript-detecting-element-visible-during-scroll#:~:text=To%20know%20wh%20the%20element%20is%20fully%20visible%20in%20viewport,height %20and%20bottom%20%3E%3D%200

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章