使用Angular从ShadowDOM中的元素自动清除输入?

问题描述 投票:1回答:1

我正在使用Ionic来创建自动完成输入,但是浏览器在使用无效数据自动填充输入时遇到了问题。我需要能够使用Angular清除它。

PS:我添加了automcomplete="off",但它不受尊重。

下面是我试图定位的Ionic ion-input的HTML:

<ion-input #inputElem
           [autocomplete]="enableBrowserAutoComplete ? 'on' : 'off'"
           [name]="name"
           (keyup)="getItems($event)"
           (tap)="handleTap($event)"
           [(ngModel)]="keyword"
           (ngModelChange)="updateModel($event)"
           (ionFocus)="onFocus($event)"
           (ionBlur)="onBlur($event)"></ion-input>

在我的组件中,我具有updateModel()函数,该函数检查更改后的输入,并在输入无效时将其清除。但是,角度变化检测不会注意到浏览器是否自动填充。

或者说,如果您在控制台中操作它:

$('input.searchbar-input.sc-ion-searchbar-md').value = 'J'

因此,如果没有有效的选择,我试图找到一种清除关键字的方法。我最成功的尝试是使用生命周期挂钩,例如OnChangesDoCheckAfterViewCheck,但是清除关键字是不够的。我必须清除影子dom内的输入,因为该值尚未传播。因此,在函数中,我必须使用promise来获取元素(我怀疑这是真正的问题)。只要我在生命周期功能内保持一个断点,哪个“有效”。第二个我删除断点,浏览器选项卡完全冻结。

@ViewChild(
  'inputElem',
  {
    read:   ElementRef,
    static: false
  }
)
private inputElem:ElementRef;

[..]

ngOnChanges():void {
    if (!this.hasFocus) {
      if (this.clearInvalidInput && this.selected === null) {
        if (this.keyword !== '') {
          this.keyword = '';
        }

        if (this.inputElem && this.inputElem.nativeElement) {
          this.inputElem.nativeElement.getInputElement().then(
              (element) => {
                if (element.value !== '') {
                  element.value = '';
                }
              }
          );
        }
     }
   }
}

我已经发布了一个解决方案作为答案,但由于感觉很hacky,所以将其保留为公开。

angular ionic-framework lifecycle shadow-dom
1个回答
0
投票

我找到了一种解决方法,但这不是首选解决方案。

ngDoCheck() {
  if (this.inputElem && this.inputElem.nativeElement) {
    if (this.inputElem.nativeElement.children && this.inputElem.nativeElement.children.length !== 0) {
      if (this.inputElem.nativeElement.children[0].children && this.inputElem.nativeElement.children[0].children.length !== 0) {
        if (this.inputElem.nativeElement.children[0].children[0].value) {
          this.inputElem.nativeElement.children[0].children[0].value = '';
        }
      }
    }
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.