自动完成功能无法正常工作吗? [英] autocomplete is not working in angular?

查看:103
本文介绍了自动完成功能无法正常工作吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为以下数据做自动完成"文本框

I want to do Autocomplete textbox for below data

Elements = [
    { id: 1, name: 'Hydrogen' },
    { id: 2, name: 'Helium' },
    { id: 3, name: 'Lithium' }


  ];

HTML

<mat-form-field class="example-full-width">
    <input type="text" placeholder="Pick one" aria-label="Number" matInput [formControl]="name"
     [matAutocomplete]="auto"  [errorStateMatcher]="matcher">
    <mat-autocomplete autoActiveFirstOption #auto="matAutocomplete" (selectionChange)="elementSelectionChange($event)">
      <mat-option *ngFor="let Element of filteredOptions | async" [value]="Element.name">
        {{ Element.name}}
      </mat-option>
    </mat-autocomplete>
        <mat-error *ngIf="myForm.hasError('required', 'name')">Please choose an name</mat-error>
  </mat-form-field>

组件

export class DialogOverviewExampleDialog implements OnInit{
  Elements = [
    { id: 1, name: 'Hydrogen' },
    { id: 2, name: 'Helium' },
    { id: 3, name: 'Lithium' }


  ];

  matcher = new MyErrorStateMatcher();
  selectedElementSymbol: any;
  myForm: FormGroup;
  symbol;
  //name;
  name: FormControl = new FormControl();
  id;
  filteredOptions: Observable<string[]>;
  OnInit() {
    this.filteredOptions = this.name.valueChanges.pipe(
      startWith(''),
      map(val => this.filter(val))
    );
  }

  filter(val: any): any[] {
    return this.Elements.filter(Element => {
      return Element.name.toLowerCase().indexOf(val.toLowerCase()) > -1;
    });
  }
  constructor(
    public dialogRef: MatDialogRef<DialogOverviewExampleDialog>,
    @Inject(MAT_DIALOG_DATA) public data: any,
    private formBuilder: FormBuilder) {


  }


}

这是我到目前为止构建的.自动完成功能不起作用,但是有人帮助我前进

This is what I built so far. autocomplete is not working but .someone help me out to move forward

演示

推荐答案

问题是您实现OnInit的方式不正确.在您的table-basic-example.ts中,将OnInit更改为ngOnInit,一切正常.

The problem is that the way you implement OnInit is incorrect. In your table-basic-example.ts, change OnInit to ngOnInit and everything will work fine.

这篇关于自动完成功能无法正常工作吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆