How do I create autocomplete in angular-material2?

I am trying to autocomplete from angular-material2

, but I am getting the following error in Visual Studio Code:

No provider for NgControl

Below is my code:

myForm.component.html

<form #form="ngForm" (ngSubmit)="getEditContactForm(form.value)" ngNativeValidate>

    <div fxLayout="column" fxLayoutGap="8px">

        <md-input-container> 
            <input mdInput placeholder="State" [mdAutocomplete]="auto" [formControl]="stateCtrl">
        </md-input-container> 
        <md-autocomplete #auto="mdAutocomplete">
            <md-option *ngFor="let state of filteredStates | async" [value]="state">
              {{ state }}
            </md-option>
        </md-autocomplete>
        <md-input-container class="example-full-width">
            <input mdInput ngModel name="country" placeholder="Χώρα" required>
        </md-input-container> 
    </div>
    <md-dialog-actions align="center" style="margin-top:50px;">
        <div fxLayout="row" fxLayoutGap="10px">
            <button md-button type="button" (click)="sidenavInside.close()">Cancel</button>
            <button md-raised-button color="primary">Save</button>
        </div>
    </md-dialog-actions>
</form>

      

myForm.component.ts

import { Component, OnInit } from '@angular/core';
import {FormControl, FormsModule, FormGroup } from '@angular/forms';
import 'rxjs/add/operator/startWith';


@Component({
  selector: 'app-admin-contact-form',
  templateUrl: './admin-contact-form.component.html',
  styleUrls: ['./admin-contact-form.component.css'],
})
export class AdminContactFormComponent implements OnInit {

  inputValue: any;

  stateCtrl: FormControl;
  filteredStates: any;

  states = [
    'Alabama',
    'Alaska',
    'Arizona',
    'Arkansas',
    'California',
    'Colorado',
  ];


  constructor() {

    this.stateCtrl = new FormControl();
    this.filteredStates = this.stateCtrl.valueChanges
        .startWith(null)
        .map(name => this.filterStates(name));

  } 

  filterStates(val: string) {
    return val ? this.states.filter(s => new RegExp(`^${val}`, 'gi').test(s))
               : this.states;
  }

  getEditContactForm(v){
    console.log(v);
  }

  ngOnInit() {
  }

}

      

Can anyone help me find how I got this error?

Thank.

+3


source to share


1 answer


When you use a form model-driven

, you need to import ReactiveFormsModule

intoAppModule



 imports { ReactiveFormsModule } from '@angular/forms';

@NgModule({
     imports: [
         ReactiveFormsModule,
     ],
     ....
 })
 export class AppModule {


 }

      

+1


source







All Articles