繁体   English   中英

在 Select Angular 中输入

[英]Input inside Select Angular

我有一小段代码,其中有一个select i option 在他们的帮助下,我遍历元素并选择我需要的元素。 关键是我需要在这个select中进行搜索。 也就是说,我既可以从列表中选择一个项目,也可以开始输入,寻找我需要的项目,然后这些项目就会显示给我。

<mat-select formControlName="targetListValue">
   <input>
   <mat-option [selected]="true" [value]="null"></mat-option>
   <mat-option *ngFor="let targetItem of targetListOptions" [value]="targetItem.id">
      {{ targetItem.name }}
   </mat-option>
</mat-select>

您可以使用“自动完成”控制的想法。

angular material提供了一个autoComplete组件,其中包含一个带有输入的选择:

自动完成是由一组建议选项增强的普通文本输入。

HTML 代码:

<form class="example-form">
  <mat-form-field class="example-full-width" appearance="fill">
    <mat-label>Number</mat-label>
    <input type="text"
           placeholder="Pick one"
           aria-label="Number"
           matInput
           [formControl]="myControl"
           [matAutocomplete]="auto">
    <mat-autocomplete autoActiveFirstOption #auto="matAutocomplete">
      <mat-option *ngFor="let option of filteredOptions | async" [value]="option">
        {{option}}
      </mat-option>
    </mat-autocomplete>
  </mat-form-field>
</form>

交易代码:

import {Component, OnInit} from '@angular/core';
import {FormControl} from '@angular/forms';
import {Observable} from 'rxjs';
import {map, startWith} from 'rxjs/operators';

/**
 * @title Highlight the first autocomplete option
 */
@Component({
  selector: 'autocomplete-auto-active-first-option-example',
  templateUrl: 'autocomplete-auto-active-first-option-example.html',
  styleUrls: ['autocomplete-auto-active-first-option-example.css'],
})
export class AutocompleteAutoActiveFirstOptionExample implements OnInit {
  myControl = new FormControl('');
  options: string[] = ['One', 'Two', 'Three'];
  filteredOptions: Observable<string[]>;

  ngOnInit() {
    this.filteredOptions = this.myControl.valueChanges.pipe(
      startWith(''),
      map(value => this._filter(value || '')),
    );
  }

  private _filter(value: string): string[] {
    const filterValue = value.toLowerCase();

    return this.options.filter(option => option.toLowerCase().includes(filterValue));
  }
}

CSS:

.example-form {
  min-width: 150px;
  max-width: 500px;
  width: 100%;
}

.example-full-width {
  width: 100%;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM