我正在尝试使用formControl制作搜索栏,但出现“无法绑定到'formControl',因为它不是'input'错误的已知属性”

时间:2019-07-09 14:25:13

标签: javascript angular typescript

^^标题

我已经在我的search-bar.module.ts中导入了FormsModule,ReactiveFormsModule,但是仍然出现错误“未捕获(承诺):错误:模板解析错误:无法绑定到'formControl',因为它不是'input'的已知属性”

有人可以告诉我我在做什么错吗?谢谢!

// search-bar.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

import { MatAutocompleteModule } from '@angular/material/autocomplete';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { SearchBarComponent } from './search-bar.component';
import { FormControl } from '@angular/forms';
@NgModule({
  declarations: [
    SearchBarComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    FormsModule,
    ReactiveFormsModule,
    MatAutocompleteModule,
    MatFormFieldModule,
    MatInputModule,
    HttpClientModule,
    FormControl
  ],
  providers: [],
  bootstrap: [ SearchBarComponent]

})
export class SearchBarModule { }
//search-bar.component.ts
import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';
import {Observable} from 'rxjs';
import {map, startWith} from 'rxjs/operators';

@Component({
  selector: 'search-bar',
  templateUrl: './search-bar.component.html',
  styleUrls: ['./search-bar.component.css'
  ]
})

export class SearchBarComponent {
  myControl = new FormControl();
  options: string[] = ['One', 'Two', 'Three'];
  filteredOptions: Observable<string[]>;

  ngOnInit() {
    this.filteredOptions = this.myControl.valueChanges
      .pipe(
        startWith(''),
        map(value => this._filter(value))
      );
  }

  private _filter(value: string): string[] {
    const filterValue = value.toLowerCase();

    return this.options.filter(option => option.toLowerCase().includes(filterValue));
  }
}

//search-bar.component.html

<mat-form-field>
    <input type="text" placeholder="Pick one" matInput [formControl]="myControl" [matAutocomplete]="auto" />

    <mat-autocomplete #auto="matAutocomplete">
        <mat-option *ngFor="let option of (filteredOptions | async)" [value]="option">
            {{ option }}
        </mat-option>
    </mat-autocomplete>
</mat-form-field>

0 个答案:

没有答案