【发布时间】:2018-02-12 20:49:04
【问题描述】:
我昨天开始使用 Angular 的 Material 模块,专门创建一个带有自定义过滤器的自动完成输入字段:https://material.angular.io/components/autocomplete/overview
我对 Angular 还是很陌生,我申请了他们网站上为我的项目提供的示例,即使只是在新项目中单独复制/粘贴他们的示例,我也会遇到相同的错误:
input-form.component.ts(75,9): error TS2684: The 'this' context of type 'void' is not assignable to method's 'this' of type 'Observable string'
与
input-form.component.ts(76,9): error TS2684: The 'this' context of type 'void' is not assignable to method's 'this' of type 'Observable<{}>'
错误位于 ts 文件中,其中:
"filteredCities = this.cityControl..." 在 ngOnInit 中。(见下文)
但我真的不明白错误是什么意思。对不起,如果这可能是一个愚蠢的问题。我仍然没有在互联网上找到答案。我错过了什么?我很想了解这个问题。
这是我的文件: input-form.component.html
<form [formGroup]="reportDataForm" (ngSubmit)="onSubmit()">
<h3>Informations de l'en-tête</h3>
<div class="form-group row">
<label for="InputCity" class="col-3 col-form-label">Commune</label>
<div class="search col-9">
<mat-form-field>
<input
type="text"
class="form-control"
id="InputCity"
matInput [formControl]="cityControl"
[matAutocomplete]="auto"
(click)="displayCities()">
</mat-form-field>
<mat-autocomplete #auto="matAutocomplete">
<mat-option *ngFor="let city of filteredCities | async" [value]="city">
{{ city }}
</mat-option>
</mat-autocomplete>
</div>
</div>
</form>
还有我的 ts 文件:
import {Component, OnInit } from '@angular/core';
import {FormControl, FormGroup, Validators} from '@angular/forms';
import {Subject} from 'rxjs/Subject';
import {Observable} from 'rxjs/Observable';
import {startWith} from 'rxjs/operator/startWith';
import {map} from 'rxjs/operator/map';
import { City } from '../../city';
import {CitiesService} from '../../data/cities.service';
@Component({
selector: 'app-input-form',
templateUrl: './input-form.component.html',
styleUrls: ['./input-form.component.css']
})
export class InputFormComponent implements OnInit {
toggle = false;
reportDataForm: FormGroup;
participantDataForm: FormGroup;
citiesListInput: string[];
cityControl: FormControl = new FormControl();
filteredCities: Observable<string[]>;
constructor(private citiesSvc: CitiesService) { }
ngOnInit() {
// Create an object that contains the data from the form and control the input
this.reportDataForm = new FormGroup({
'city': new FormControl(null, [Validators.required]),
});
this.filteredCities = this.cityControl.valueChanges
.pipe(
startWith(''),
map(val => this.filter(val))
);
}
displayCities() {
this.citiesListInput = this.citiesSvc.citiesList;
}
filter(val: string): string[] {
return this.citiesSvc.citiesList.filter(city =>
city.toUpperCase().indexOf(val.toUpperCase()) === 0);
}
这是我的服务,稍后将连接到数据库。现在它只包含一个列表:
import {Injectable} from '@angular/core';
@Injectable()
export class CitiesService {
citiesList = ['AFFOUX', 'LYON', 'DARDILLY', 'ATOOINE', 'AMELOTT'];
}
版本:
"typescript": "~2.4.2"
"rxjs": "^5.5.2"
【问题讨论】:
标签: angular filter autocomplete angular-material2