这是html
<form>
<mat-form-field class="container">
<input type="text" matInput [formControl]="usersForm" [matAutocomplete]="auto" >
<!-- CREATE AUTO COMPLETE PANEL WITH OPTIONS. -->
<mat-autocomplete #auto="matAutocomplete">
<mat-option *ngFor="let result of filteredUsers" [value]="result.id">
{{ result.name }}
</mat-option>
</mat-autocomplete>
</mat-form-field>
</form>
这是课程
export class User {
constructor(public id: number, public name: string) {}
}
这是组件
export class CertificationComponent implements OnInit {
filteredUsers: User[] = [];
usersForm = new FormControl();
isLoading = false;
constructor(private fb: FormBuilder, private service: Service) {}
ngOnInit() {
this.usersForm.valueChanges.subscribe(
term => {
if (term != '') {
this.service.search(term).subscribe(
data => {
console.log(data);
this.filteredUsers = data as any[];
})
}
})
}
displayFn(user: User) {
if (user) { return user.name; }
}
}
这是服务。我正在创建一个虚拟对象,该对象可以传递任何输入,但它似乎没有出现在下拉列表中。 我在组件中获得了用户虚拟数据,但在视图下拉列表中却没有。
@Injectable()
export class CertificationService {
user : User = {id:1, "name":"abcd"};
users: User[] = [this.user];
constructor(private http: HttpClient) {}
search(name:String): Observable<any> {
return of(this.users);
}
}