Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
521 views
in Technique[技术] by (71.8m points)

autocomplete is not working in angular?

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>

component

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

demo

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...