【问题标题】:Angular mat-autocomplete with highlight pipe issue带有突出显示管道问题的角垫自动完成
【发布时间】:2019-09-20 13:46:08
【问题描述】:

我有一个场景,我正在使用带有自定义突出显示管道的 mat-autocomplete。一切正常,当我从自动完成中选择一个值然后我尝试重置表单时出现问题,表单正在重置但自动完成中的值仍然突出显示。

highlight.pipe.ts

transform(text: string, search): string {
    const pattern = search
      .replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&")
      .split(' ')
      .filter(t => t.length > 0)
      .join('|');
    const regex = new RegExp(pattern, 'gi');
    return search ? text.replace(regex, match => `<b>${match}</b>`) : text;
  }

component.html

<form class="example-form">
    <mat-form-field class="example-full-width">
        <input matInput placeholder="State" aria-label="State" [matAutocomplete]="auto" [formControl]="stateCtrl">
        <mat-autocomplete #auto="matAutocomplete">
            <mat-option *ngFor="let state of filteredStates | async" [value]="state.name">
        <span [innerHTML]="state.name | highLight: toHighlight"></span>
                <span></span>
            </mat-option>
        </mat-autocomplete>
    </mat-form-field>
</form>

Stackblitz Demo

单击重置时,我不希望突出显示任何值。有什么办法可以解决这个问题。

提前致谢

【问题讨论】:

  • 我什至无法在 stackblitz 中重现该问题?我开始打字,选择了一个选项,然后单击了重置。再次单击自动完成时,没有突出显示任何内容。我错过了一些步骤吗?
  • 我刚刚添加了 imrane 给出的修复,您可以通过在重置方法中删除 toHighlight="" 并在输入标签上注释掉 keyup 方法来重现该问题
  • 好的,但是你的问题解决了,对吧? :)
  • 我认为这不是一个理想的解决方案。这只是一个临时修复。试试看能不能永久修复

标签: angular angular-material angular7 highlight angular-pipe


【解决方案1】:

您可以将多个参数传递给管道,因此您可以传递stateCtrl 的值,并将其添加到您的条件中以检查值是否也存在:

<span [innerHTML]="state.name | highLight: toHighlight : stateCtrl.value"></span>

然后对该值进行额外检查:

transform(text: string, search: string, ctrlValue: string): string {
  // ....
  return (search && ctrlValue) ? text.replace(regex, match => `<b>${match}</b>`) : text;
}

Your forked STACKBLITZ

【讨论】:

    【解决方案2】:

    你必须在reset函数中再次reset toHighlight=''...但是你又遇到了一个烦人的小问题,在你删除你输入的内容后,即使该字段为空,它仍然会记住最后一个字符和突出显示它..所以您现在的解决方案是始终重置表单,但您必须继续努力

    【讨论】:

      猜你喜欢
      • 2023-03-09
      • 1970-01-01
      • 2019-05-19
      • 1970-01-01
      • 2011-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-24
      相关资源
      最近更新 更多