Autocomplete自动完成

输入框自动完成功能。

何时使用

需要自动完成时。

  1. import { NzAutocompleteModule } from 'ng-zorro-antd/auto-complete';

代码演示

Autocomplete自动完成 - 图1

基本使用

基本使用。通过 nzDataSource 设置自动完成的数据源

  1. import { Component, ViewEncapsulation } from '@angular/core';
  2. @Component({
  3. selector: 'nz-demo-auto-complete-basic',
  4. encapsulation: ViewEncapsulation.None,
  5. template: `
  6. <div class="example-input">
  7. <input placeholder="input here" nz-input [(ngModel)]="inputValue" (input)="onInput($event.target?.value)" [nzAutocomplete]="auto" />
  8. <nz-autocomplete [nzDataSource]="options" nzBackfill #auto></nz-autocomplete>
  9. </div>
  10. `
  11. })
  12. export class NzDemoAutoCompleteBasicComponent {
  13. inputValue: string;
  14. options: string[] = [];
  15. onInput(value: string): void {
  16. this.options = value ? [value, value + value, value + value + value] : [];
  17. }
  18. }

Autocomplete自动完成 - 图2

自定义选项

也可以直接传 nz-auto-option 作为 nz-autocomplete 的 Content,而非使用 nzDataSource

  1. import { Component, ViewEncapsulation } from '@angular/core';
  2. @Component({
  3. selector: 'nz-demo-auto-complete-options',
  4. encapsulation: ViewEncapsulation.None,
  5. template: `
  6. <div class="example-input">
  7. <input placeholder="input here" nz-input [(ngModel)]="inputValue" (input)="onInput($event)" [nzAutocomplete]="auto" />
  8. <nz-autocomplete #auto>
  9. <nz-auto-option *ngFor="let option of options" [nzValue]="option">{{ option }}</nz-auto-option>
  10. </nz-autocomplete>
  11. </div>
  12. `
  13. })
  14. export class NzDemoAutoCompleteOptionsComponent {
  15. inputValue: string;
  16. options: string[] = [];
  17. onInput(e: Event): void {
  18. const value = (e.target as HTMLInputElement).value;
  19. if (!value || value.indexOf('@') >= 0) {
  20. this.options = [];
  21. } else {
  22. this.options = ['gmail.com', '163.com', 'qq.com'].map(domain => `${value}@${domain}`);
  23. }
  24. }
  25. }

Autocomplete自动完成 - 图3

不区分大小写

不区分大小写的 AutoComplete

  1. import { Component, ViewEncapsulation } from '@angular/core';
  2. @Component({
  3. selector: 'nz-demo-auto-complete-non-case-sensitive',
  4. encapsulation: ViewEncapsulation.None,
  5. template: `
  6. <div class="example-input">
  7. <input placeholder="try to type \`b\`" nz-input [(ngModel)]="inputValue" (ngModelChange)="onChange($event)" [nzAutocomplete]="auto" />
  8. <nz-autocomplete [nzDataSource]="filteredOptions" #auto></nz-autocomplete>
  9. </div>
  10. `
  11. })
  12. export class NzDemoAutoCompleteNonCaseSensitiveComponent {
  13. inputValue: string;
  14. filteredOptions: string[] = [];
  15. options = ['Burns Bay Road', 'Downing Street', 'Wall Street'];
  16. constructor() {
  17. this.filteredOptions = this.options;
  18. }
  19. onChange(value: string): void {
  20. this.filteredOptions = this.options.filter(option => option.toLowerCase().indexOf(value.toLowerCase()) !== -1);
  21. }
  22. }

Autocomplete自动完成 - 图4

查询模式 - 不确定类目

查询模式: 不确定类目 示例。

  1. import { Component, ViewEncapsulation } from '@angular/core';
  2. @Component({
  3. selector: 'nz-demo-auto-complete-uncertain-category',
  4. encapsulation: ViewEncapsulation.None,
  5. template: `
  6. <div class="example-input">
  7. <nz-input-group nzSearch nzSize="large" [nzAddOnAfter]="suffixIconButton">
  8. <input placeholder="input here" nz-input [(ngModel)]="inputValue" (input)="onChange($event)" [nzAutocomplete]="auto" />
  9. </nz-input-group>
  10. <ng-template #suffixIconButton>
  11. <button nz-button nzType="primary" nzSize="large" nzSearch>
  12. <i nz-icon nzType="search" nzTheme="outline"></i>
  13. </button>
  14. </ng-template>
  15. <nz-autocomplete #auto>
  16. <nz-auto-option class="global-search-item" *ngFor="let option of options" [nzValue]="option.category">
  17. Found {{ option.value }} on
  18. <a
  19. class="global-search-item-desc"
  20. [href]="'https://s.taobao.com/search?q=' + option.value"
  21. target="_blank"
  22. rel="noopener noreferrer"
  23. >
  24. {{ option.category }}
  25. </a>
  26. <span class="global-search-item-count">{{ option.count }} results</span>
  27. </nz-auto-option>
  28. </nz-autocomplete>
  29. </div>
  30. `,
  31. styles: [
  32. `
  33. .global-search-item {
  34. display: flex;
  35. }
  36. .global-search-item-desc {
  37. flex: auto;
  38. text-overflow: ellipsis;
  39. overflow: hidden;
  40. }
  41. .global-search-item-count {
  42. flex: none;
  43. }
  44. `
  45. ]
  46. })
  47. export class NzDemoAutoCompleteUncertainCategoryComponent {
  48. inputValue: string;
  49. options: Array<{ value: string; category: string; count: number }> = [];
  50. onChange(e: Event): void {
  51. const value = (e.target as HTMLInputElement).value;
  52. this.options = new Array(this.getRandomInt(5, 15))
  53. .join('.')
  54. .split('.')
  55. .map((_item, idx) => ({
  56. value,
  57. category: `${value}${idx}`,
  58. count: this.getRandomInt(200, 100)
  59. }));
  60. }
  61. private getRandomInt(max: number, min: number = 0): number {
  62. return Math.floor(Math.random() * (max - min + 1)) + min;
  63. }
  64. }

Autocomplete自动完成 - 图5

使用对象类型选项

nzValuengModel 类型为 object 时使用 compareWith(SelectControlValueAccessor).

  1. import { Component, ViewEncapsulation } from '@angular/core';
  2. interface Option {
  3. label: string;
  4. value: string;
  5. age: number;
  6. }
  7. @Component({
  8. selector: 'nz-demo-auto-complete-object-value',
  9. encapsulation: ViewEncapsulation.None,
  10. template: `
  11. <div class="example-input">
  12. <input placeholder="input here" nz-input [(ngModel)]="inputValue" [nzAutocomplete]="auto" />
  13. <nz-autocomplete #auto [compareWith]="compareFun">
  14. <nz-auto-option *ngFor="let option of options" [nzValue]="option" [nzLabel]="option.label">
  15. {{ option.label }}
  16. </nz-auto-option>
  17. </nz-autocomplete>
  18. </div>
  19. `
  20. })
  21. export class NzDemoAutoCompleteObjectValueComponent {
  22. inputValue: Option = { label: 'Lucy', value: 'lucy', age: 20 };
  23. options: Option[] = [
  24. { label: 'Lucy', value: 'lucy', age: 20 },
  25. { label: 'Jack', value: 'jack', age: 22 }
  26. ];
  27. compareFun = (o1: Option | string, o2: Option) => {
  28. if (o1) {
  29. return typeof o1 === 'string' ? o1 === o2.label : o1.value === o2.value;
  30. } else {
  31. return false;
  32. }
  33. };
  34. }

Autocomplete自动完成 - 图6

自定义输入组件

自定义输入组件。

  1. import { Component, ViewEncapsulation } from '@angular/core';
  2. @Component({
  3. selector: 'nz-demo-auto-complete-custom',
  4. encapsulation: ViewEncapsulation.None,
  5. template: `
  6. <div class="example-input">
  7. <textarea
  8. placeholder="input here"
  9. nz-input
  10. row="4"
  11. [(ngModel)]="inputValue"
  12. (input)="onInput($event.target?.value)"
  13. [nzAutocomplete]="auto"
  14. ></textarea>
  15. <nz-autocomplete #auto>
  16. <nz-auto-option *ngFor="let option of options" [nzValue]="option">{{ option }}</nz-auto-option>
  17. </nz-autocomplete>
  18. </div>
  19. `
  20. })
  21. export class NzDemoAutoCompleteCustomComponent {
  22. inputValue: string;
  23. options: string[] = [];
  24. onInput(value: string): void {
  25. this.options = value ? [value, value + value, value + value + value] : [];
  26. }
  27. }

Autocomplete自动完成 - 图7

查询模式 - 确定类目

查询模式: 确定类目 示例。

  1. import { Component, OnInit, ViewEncapsulation } from '@angular/core';
  2. export interface AutocompleteOptionGroups {
  3. title: string;
  4. count?: number;
  5. children?: AutocompleteOptionGroups[];
  6. }
  7. @Component({
  8. selector: 'nz-demo-auto-complete-certain-category',
  9. encapsulation: ViewEncapsulation.None,
  10. template: `
  11. <div class="example-input">
  12. <nz-input-group nzSize="large" [nzSuffix]="suffixIcon">
  13. <input placeholder="input here" nz-input [(ngModel)]="inputValue" (ngModelChange)="onChange($event)" [nzAutocomplete]="auto" />
  14. </nz-input-group>
  15. <ng-template #suffixIcon>
  16. <i nz-icon nzType="search"></i>
  17. </ng-template>
  18. <nz-autocomplete #auto>
  19. <nz-auto-optgroup *ngFor="let group of optionGroups" [nzLabel]="groupTitle">
  20. <ng-template #groupTitle>
  21. <span
  22. >{{ group.title }}
  23. <a class="more-link" href="https://www.google.com/search?q=ng+zorro" target="_blank">更多</a>
  24. </span>
  25. </ng-template>
  26. <nz-auto-option *ngFor="let option of group.children" [nzLabel]="option.title" [nzValue]="option.title">
  27. {{ option.title }}
  28. <span class="certain-search-item-count">{{ option.count }} 人 关注</span>
  29. </nz-auto-option>
  30. </nz-auto-optgroup>
  31. </nz-autocomplete>
  32. </div>
  33. `,
  34. styles: [
  35. `
  36. .certain-search-item-count {
  37. position: absolute;
  38. color: #999;
  39. right: 16px;
  40. }
  41. .more-link {
  42. float: right;
  43. }
  44. `
  45. ]
  46. })
  47. export class NzDemoAutoCompleteCertainCategoryComponent implements OnInit {
  48. inputValue: string;
  49. optionGroups: AutocompleteOptionGroups[];
  50. constructor() {}
  51. onChange(value: string): void {
  52. console.log(value);
  53. }
  54. ngOnInit(): void {
  55. setTimeout(() => {
  56. this.optionGroups = [
  57. {
  58. title: '话题',
  59. children: [
  60. {
  61. title: 'AntDesign',
  62. count: 10000
  63. },
  64. {
  65. title: 'AntDesign UI',
  66. count: 10600
  67. }
  68. ]
  69. },
  70. {
  71. title: '问题',
  72. children: [
  73. {
  74. title: 'AntDesign UI 有多好',
  75. count: 60100
  76. },
  77. {
  78. title: 'AntDesign 是啥',
  79. count: 30010
  80. }
  81. ]
  82. },
  83. {
  84. title: '文章',
  85. children: [
  86. {
  87. title: 'AntDesign 是一个设计语言',
  88. count: 100000
  89. }
  90. ]
  91. }
  92. ];
  93. }, 1000);
  94. }
  95. }

API

  1. <input nz-input [(ngModel)]="value" [nzAutocomplete]="auto">
  2. <nz-autocomplete [nzDataSource]="['12345', '23456', '34567']" #auto></nz-autocomplete>
  1. <input nz-input [(ngModel)]="value" [nzAutocomplete]="auto">
  2. <nz-autocomplete #auto>
  3. <nz-auto-option [nzValue]="'12345'">12345</nz-auto-option>
  4. <nz-auto-option [nzValue]="'23456'">23456</nz-auto-option>
  5. <nz-auto-option [nzValue]="'34567'">34567</nz-auto-option>
  6. </nz-autocomplete>

[nzAutocomplete]directive

属性说明类型默认值
[nzAutocomplete]用于绑定 nzAutocomplete 组件NzAutocompleteComponent-

nz-autocompletecomponent

属性说明类型默认值
[nzBackfill]使用键盘选择选项的时候把选中项回填到输入框中booleanfalse
[nzDataSource]自动完成的数据源AutocompleteDataSource-
[nzDefaultActiveFirstOption]是否默认高亮第一个选项。booleantrue
[nzWidth]自定义宽度单位 pxnumber触发元素宽度
[nzOverlayClassName]下拉根元素的类名称string-
[nzOverlayStyle]下拉根元素的样式object-
[compareWith]SelectControlValueAccessor 相同(o1: any, o2: any) => boolean(o1: any, o2: any) => o1===o2

nz-auto-optioncomponent

属性说明类型默认值
[nzValue]绑定到触发元素 ngModel 的值any-
[nzLabel]填入触发元素显示的值string-
[nzDisabled]禁用选项booleanfalse