【问题标题】:custom typeahead implemented, additional feature required实现了自定义预输入,需要额外的功能
【发布时间】:2018-06-05 17:14:04
【问题描述】:

我在 Angular 中创建了一个自定义预输入。查看代码here

我必须在这里再添加两个功能,但我不知道如何实现。

  1. 当用户开始输入并显示选项时,显示的选项中匹配的字符应该是不同的颜色,比如蓝色或红色

  2. 现在可以通过鼠标单击从显示的菜单中选择选项,我还想添加用于导航和从键盘选择的选项。

请告知我如何继续实施上述这些功能。

【问题讨论】:

    标签: javascript css angular typeahead


    【解决方案1】:

    对于第一个功能,您可以执行以下操作:

    使用以下代码创建 highlight.pipe.ts 文件:

    import { PipeTransform, Pipe } from '@angular/core';
    
    @Pipe({ name: 'highlight' }) export class HighlightPipe implements PipeTransform {   transform(text: string, search): string {
        if (search && text) {
          let pattern = search.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
          pattern = pattern.split(' ').filter((t) => {
            return t.length > 0;
          }).join('|');
          const regex = new RegExp(pattern, 'gi');
    
          return text.replace(regex, (match) => `<span class="search-highlight">${match}</span>`);
        } else {
          return text;
        }   } }
    

    在 app.module.ts 中注入这个管道

    import { HighlightPipe } from './highlight.pipe';
    

    更新你的应用组件

    <div class="parent">
        <div>
            <h5>Sample Custom Typeahead</h5>
            <p>Try typing "Win" or "Mob" in input box below</p>
            <input type="text" [(ngModel)]="searchByThis" (keyup)="showDropdown()">
        </div>
        <div>
            <div (clickOutside)="closeDropDown()">
                <div class='search-drop-down' *ngIf="displayDropdown">
    
                    <div (click)='selectValue(product)' class='search-results' *ngFor="let product of sampleItemDetails | searchFilter: searchByThis ">
    
                        <div [innerHTML]="product.name  | highlight : searchByThis">
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    

    别忘了更新你的 CSS:app.component.css

    :host ::ng-deep .search-highlight{
      background-color: #F2E366;
    }
    

    我已经提到了这个gist

    【讨论】:

    • 哇!!感谢@Syed Arshad,这个解决方案有效。也请发布第二个功能。
    • 太棒了,抱歉回复晚了。工作很忙。稍后会检查下一个。
    猜你喜欢
    • 1970-01-01
    • 2011-05-28
    • 1970-01-01
    • 1970-01-01
    • 2011-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多