如何转换为可编辑的选择框?

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

我有一个带引导程序的角度5项目。在我的一个组件html中,我有一个选择框。当我点击它时,会显示一个下拉项目列表,我可以选择一个。但是我希望用户键入一些字符串,以便缩小下拉项目。这是我当前的代码片段,我知道如何将选择框转换为可编辑的代码片段。

   <select formControlName="contactList" [compareWith]="compareResource">
      <option value="" disabled>{{ 'PLACEHOLDERS.CONTACT_LIST' | translate }}</option>
      <option *ngFor="let contactList of contactLists" [ngValue]="contactList">{{ contactList.name }}</option>
    </select>

我想将现有的选择框代码转换为可编辑的选择框。请分享您的想法。我是UI编程的新手。谢谢

angular bootstrap-4 angular-ui ui-select2
2个回答
1
投票

这可以通过使用ng-select来实现

安装-选择

npm install --save @ng-select/ng-select

app.module.ts

将其导入模块

import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { NgSelectModule } from '@ng-select/ng-select';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    BrowserModule,
    FormsModule,
    CommonModule,
    NgSelectModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

style.css文件

导入ng-select默认样式

@import "~@ng-select/ng-select/themes/default.theme.css";

app.component.html

通过将nameList绑定为下拉列表和搜索功能的items数组来创建ng-select下拉列表

<div style="text-align:center">
  Editable Dropdown
</div>

<div style="width:300px; height:200px">
  <ng-select class="autocomplete" dropdownPosition="bottom" [searchFn]="searchName" [items]="nameList"
    [(ngModel)]="selectedName" [dropdownPosition]="'auto'">
    <ng-template ng-header-tmp>
      <div class="container-fluid">
        <div class="row">
          <div class="col-md-6">Username</div>
        </div>
      </div>
    </ng-template>
    <ng-template ng-label-tmp let-item="item">
      <span>{{item}}</span>
    </ng-template>
    <ng-template ng-option-tmp let-item="item" let-index="index">
      <div class="container-fluid">
        <div class="row">
          <div class="col-md-4">{{item}}</div>
        </div>
      </div>
    </ng-template>
  </ng-select>
</div>

app.component.ts

初始化nameList并定义搜索功能。在这里,我将返回包含从下拉列表中输入的值的名称

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  selectedName: string;
  nameList: string[];

  constructor() { }

  ngOnInit() {
    this.nameList = this.getNameList();
  }

  getNameList(): string[] {
    return [
      'Adam',
      'Alex',
      'Bob',
      'Bennt',
      'Cathrina',
      'Dug',
      'Suzzy',
      'Amy',
      'Milan'
    ];
  }

  searchName(filter: string, item: string) {
    filter = filter.toLocaleLowerCase();
    return (item.toLocaleLowerCase().indexOf(filter) > -1);
  }
}

0
投票

您可以使用角度材质自动完成过滤器来获得所需的结果。 - qazxsw poi

© www.soinside.com 2019 - 2024. All rights reserved.