Autocomplete

Autocomplete function of input field.

When To Use#

When there is a need for autocomplete functionality.

Import this Component Individually#

You can get more detail here.

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

Examples

Basic Usage, set nzDataSource of nz-autocomplete with dataSource property.

expand codeexpand code
import { Component, ViewEncapsulation } from '@angular/core';

@Component({
  selector: 'nz-demo-auto-complete-basic',
  encapsulation: ViewEncapsulation.None,
  template: `
    <div class="example-input">
      <input
        placeholder="input here"
        nz-input
        [(ngModel)]="inputValue"
        (input)="onInput($event.target?.value)"
        [nzAutocomplete]="auto"
      />
      <nz-autocomplete nzBackfill #auto>
        <nz-auto-option *ngFor="let option of options" [nzValue]="option">
          {{ option }}
        </nz-auto-option>
      </nz-autocomplete>
    </div>
  `
})
export class NzDemoAutoCompleteBasicComponent {
  inputValue: string;
  options: string[] = [];

  onInput(value: string): void {
    this.options = value ? [value, value + value, value + value + value] : [];
  }
}

Customize Input Component

expand codeexpand code
import { Component, ViewEncapsulation } from '@angular/core';

@Component({
  selector: 'nz-demo-auto-complete-custom',
  encapsulation: ViewEncapsulation.None,
  template: `
    <div class="example-input">
      <textarea
        placeholder="input here"
        nz-input
        row="4"
        [(ngModel)]="inputValue"
        (input)="onInput($event.target?.value)"
        [nzAutocomplete]="auto"
      ></textarea>
      <nz-autocomplete #auto>
        <nz-auto-option *ngFor="let option of options" [nzValue]="option">{{ option }}</nz-auto-option>
      </nz-autocomplete>
    </div>
  `
})
export class NzDemoAutoCompleteCustomComponent {
  inputValue: string;
  options: string[] = [];

  onInput(value: string): void {
    this.options = value ? [value, value + value, value + value + value] : [];
  }
}
expand codeexpand code
import { ChangeDetectionStrategy, Component, OnInit, ViewEncapsulation } from '@angular/core';

@Component({
  selector: 'nz-demo-auto-complete-certain-category',
  encapsulation: ViewEncapsulation.None,
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <div class="example-input">
      <nz-input-group nzSize="large" [nzSuffix]="suffixIcon">
        <input
          placeholder="input here"
          nz-input
          [(ngModel)]="inputValue"
          (ngModelChange)="onChange($event)"
          [nzAutocomplete]="auto"
        />
      </nz-input-group>
      <ng-template #suffixIcon>
        <i nz-icon nzType="search"></i>
      </ng-template>
      <nz-autocomplete #auto>
        <nz-auto-optgroup *ngFor="let group of optionGroups" [nzLabel]="groupTitle">
          <ng-template #groupTitle>
            <span
              >{{ group.title }}
              <a class="more-link" href="https://www.google.com/search?q=ng+zorro" target="_blank">更多</a>
            </span>
          </ng-template>
          <nz-auto-option *ngFor="let option of group.children" [nzLabel]="option.title" [nzValue]="option">
            {{ option.title }}
            <span class="certain-search-item-count">{{ option.count }} 人 关注</span>
          </nz-auto-option>
        </nz-auto-optgroup>
      </nz-autocomplete>
    </div>
  `,
  styles: [
    `
      .certain-search-item-count {
        position: absolute;
        color: #999;
        right: 16px;
      }

      .more-link {
        float: right;
      }
    `
  ]
})
export class NzDemoAutoCompleteCertainCategoryComponent implements OnInit {
  inputValue: string;
  optionGroups: any[];

  onChange(value: any): void {
    console.log(value);
  }

  ngOnInit(): void {
    setTimeout(() => {
      this.optionGroups = [
        {
          title: '话题',
          children: [
            {
              title: 'AntDesign',
              count: 10000
            },
            {
              title: 'AntDesign UI',
              count: 10600
            }
          ]
        },
        {
          title: '问题',
          children: [
            {
              title: 'AntDesign UI 有多好',
              count: 60100
            },
            {
              title: 'AntDesign 是啥',
              count: 30010
            }
          ]
        },
        {
          title: '文章',
          children: [
            {
              title: 'AntDesign 是一个设计语言',
              count: 100000
            }
          ]
        }
      ];
    }, 1000);
  }
}

You could pass nz-auto-option as Content of nz-autocomplete, instead of using nzDataSource`.

expand codeexpand code
import { Component, ViewEncapsulation } from '@angular/core';

@Component({
  selector: 'nz-demo-auto-complete-options',
  encapsulation: ViewEncapsulation.None,
  template: `
    <div class="example-input">
      <input
        placeholder="input here"
        nz-input
        [(ngModel)]="inputValue"
        (ngModelChange)="onChange($event)"
        [nzAutocomplete]="auto"
      />
      <nz-autocomplete #auto>
        <nz-auto-option *ngFor="let option of options" [nzValue]="option">{{ option }}</nz-auto-option>
      </nz-autocomplete>
    </div>
  `
})
export class NzDemoAutoCompleteOptionsComponent {
  inputValue: string;
  options: string[] = [];

  onChange(value: string): void {
    if (!value || value.indexOf('@') >= 0) {
      this.options = [];
    } else {
      this.options = ['gmail.com', '163.com', 'qq.com'].map(domain => `${value}@${domain}`);
    }
  }
}

A non-case-sensitive AutoComplete

expand codeexpand code
import { Component, ViewEncapsulation } from '@angular/core';

@Component({
  selector: 'nz-demo-auto-complete-non-case-sensitive',
  encapsulation: ViewEncapsulation.None,
  template: `
    <div class="example-input">
      <input
        placeholder="try to type \`b\`"
        nz-input
        [(ngModel)]="inputValue"
        (input)="onInput($event.target?.value)"
        [nzAutocomplete]="auto"
      />
      <nz-autocomplete [nzDataSource]="filteredOptions" #auto> </nz-autocomplete>
    </div>
  `
})
export class NzDemoAutoCompleteNonCaseSensitiveComponent {
  inputValue: string;
  filteredOptions: string[] = [];
  options = ['Burns Bay Road', 'Downing Street', 'Wall Street'];

  constructor() {
    this.filteredOptions = this.options;
  }

  onInput(value: string): void {
    this.filteredOptions = this.options.filter(option => option.toLowerCase().indexOf(value.toLowerCase()) === 0);
  }
}
expand codeexpand code
import { Component, ViewEncapsulation } from '@angular/core';

@Component({
  selector: 'nz-demo-auto-complete-uncertain-category',
  encapsulation: ViewEncapsulation.None,
  template: `
    <div class="example-input">
      <nz-input-group nzSearch nzSize="large" [nzAddOnAfter]="suffixIconButton">
        <input
          placeholder="input here"
          nz-input
          [(ngModel)]="inputValue"
          (ngModelChange)="onChange($event)"
          [nzAutocomplete]="auto"
        />
      </nz-input-group>
      <ng-template #suffixIconButton>
        <button nz-button nzType="primary" nzSize="large" nzSearch>
          <i nz-icon nzType="search" nzTheme="outline"></i>
        </button>
      </ng-template>
      <nz-autocomplete #auto>
        <nz-auto-option *ngFor="let option of options" [nzValue]="option.category">
          {{ option.value }} 在
          <a [href]="'https://s.taobao.com/search?q=' + option.query" target="_blank" rel="noopener noreferrer">
            {{ option.category }}
          </a>
          区块中
          <span class="global-search-item-count">约 {{ option.count }} 个结果</span>
        </nz-auto-option>
      </nz-autocomplete>
    </div>
  `,
  styles: [
    `
      .global-search-item-count {
        position: absolute;
        right: 16px;
      }
    `
  ]
})
export class NzDemoAutoCompleteUncertainCategoryComponent {
  inputValue: string;
  options: Array<{ value: string; category: string; count: number }> = [];

  onChange(value: string): void {
    this.options = new Array(this.getRandomInt(15, 5))
      .join('.')
      .split('.')
      .map((_item, idx) => ({
        value,
        category: `${value}${idx}`,
        count: this.getRandomInt(200, 100)
      }));
  }

  private getRandomInt(max: number, min: number = 0): number {
    return Math.floor(Math.random() * (max - min + 1)) + min;
  }
}

API#

<input nz-input [(ngModel)]="value" [nzAutocomplete]="auto">
<nz-autocomplete [nzDataSource]="['12345', '23456', '34567']" #auto></nz-autocomplete>
<input nz-input [(ngModel)]="value" [nzAutocomplete]="auto">
<nz-autocomplete #auto>
  <nz-auto-option [nzValue]="'12345'">12345</nz-auto-option>
  <nz-auto-option [nzValue]="'23456'">23456</nz-auto-option>
  <nz-auto-option [nzValue]="'34567'">34567</nz-auto-option>
</nz-autocomplete>

[nzAutocomplete]#

PropertyDescriptionTypeDefault
[nzAutocomplete]used to bind nzAutocomplete componentsNzAutocompleteComponent-

nz-autocomplete#

PropertyDescriptionTypeDefault
[nzBackfill]backfill selected item the input when using keyboardbooleanfalse
[nzDataSource]Data source for autocompleteAutocompleteDataSource-
[nzDefaultActiveFirstOption]Whether active first option by defaultbooleantrue
[nzWidth]Custom width, unit pxnumbertrigger element width
[nzOverlayClassName]Class name of the dropdown root elementstring-
[nzOverlayStyle]Style of the dropdown root elementobject-

nz-auto-option#

PropertyDescriptionTypeDefault
[nzValue]bind ngModel of the trigger elementany-
[nzLabel]display value of the trigger elementstring-
[nzDisabled]disabled optionbooleanfalse