html - FormControl ไม่ได้รับการจัดเตรียมโดย directive ที่ใช้ได้ใด ๆ
FormControl กำลังประสบปัญหากับคำสั่งกำกับ...
ฉันกำลังพยายามที่จะนำระบบเติมข้อความอัตโนมัติมาใช้ในช่องป้อนข้อมูลของฉัน ฉันกำลังใช้คู่มือ angular-material ดังต่อไปนี้ จนถึงขั้นที่ฉันก็ได้คัดลอกและวางโค้ด TypeScript และ HTML ของพวกเขาโดยตรงเพื่อลองทดสอบ: https://material.angular.io/components/autocomplete/overview
ฉันยังคงได้รับข้อผิดพลาดใน FormControl ใน HTML ที่ระบุว่า: "Property FormControl ไม่ได้รับจาก directive ที่เกี่ยวข้องใด ๆ หรือจาก element ของ input ข้อมูลการตรวจสอบ: รายงานคุณสมบัติ เหตุการณ์ หรือการผูก directive เชิงโครงสร้างที่ไม่กำหนดใน elements."
HTML CODE:
<form class="example-form">
<mat-form-field class="example-full-width">
<input type="text" placeholder="Pick one" aria-label="Number" 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>
</form>
TS CODE:
import {Component, OnInit} from '@angular/core';
import {FormControl} from '@angular/forms';
import {Observable} from 'rxjs';
import {map, startWith} from 'rxjs/operators';
@Component({
selector: 'mySelector',
templateUrl: 'myTemplate.html',
styleUrls: ['myCSS.css'],
})
export class myExportClass implements OnInit {
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));
}
}
คำตอบ #1
ตามที่ระบุไว้ในเอกสาร: "สำหรับตัวอย่างนี้ ให้แน่ใจว่าคุณได้นำเข้า ReactiveFormsModule จาก @angular/forms เข้าไปใน NgModule ของคุณ"
ดังนั้นต้องตรวจสอบให้แน่ใจว่า app.module ของคุณมีโมดูล เช่น:
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent,
],
imports: [
FormsModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
