我正在考虑使用 Angular Material 自动完成模块,就像他们在这里有一个示例一样。他们在概述中说可以使用模板驱动的表单。所以我想我会试一试。
模板:
<form (ngSubmit)="doSmth()" #f="ngForm">
<mat-form-field>
<input type="text" required id="name" (ngModel)="myControl" name="name" matInput [matAutocomplete]="auto">
<mat-autocomplete #auto="matAutocomplete">
<mat-option *ngFor="let option of filteredOptions | async" [value]="option">{{ option }}</mat-option>
</mat-autocomplete>
</mat-form-field>
<button type="submit" [disabled]="!f.form.valid">Click</button>
</form>
零件:
@Component({
selector: 'autocomplete-filter-example',
templateUrl: 'autocomplete-filter-example.html',
styleUrls: ['autocomplete-filter-example.css'],
})
export class AutocompleteFilterExample implements OnInit {
myControl: FormControl();
options: string[] = ['One', 'Two', 'Three'];
filteredOptions: Observable<string[]>;
ngOnInit() {
this.filteredOptions = this.myControl.valueChanges
.pipe(
startWith(''),
map((value: string) => this.filter(value))
);
}
private filter(value: string): string[] {
const filterValue = value.toLowerCase();
return this.options.filter(option => option.toLowerCase().includes(filterValue));
}
}
麻烦的是,当我运行它时,我得到一个错误:
AppComponent.html:1 ERROR TypeError: Cannot read property 'valueChanges' of undefined
所以我猜 ngModel 是在 init 之后绑定的?或者为什么这不起作用?我需要使用单独的实例FormControl吗?