我想在MdAutocomplete
中使用Angular Material2的*ngFor
组件重复组件。
但是我收到以下错误:
ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
at NgForOf.ngOnChanges (common.es5.js:1689)
at checkAndUpdateDirectiveInline (core.es5.js:10724)
at checkAndUpdateNodeInline (core.es5.js:12117)
at checkAndUpdateNode (core.es5.js:12085)
at debugCheckAndUpdateNode (core.es5.js:12715)
at debugCheckDirectivesFn (core.es5.js:12656)
at Object.View_WorkCardComponent_0.co [as updateDirectives] (WorkCardComponent.html:8)
at Object.debugUpdateDirectives [as updateDirectives] (core.es5.js:12641)
at checkAndUpdateView (core.es5.js:12053)
at callViewAction (core.es5.js:12367)
这是HTML(work-card.component.html):
<md-input-container>
<input mdInput placeholder="Project" [formControl]="projectCtrl" [mdAutocomplete]="auto" >
</md-input-container>
<md-autocomplete #auto [displayWith]="displayFn">
<md-option *ngFor="let project of filteredProjects" [value]="project.name">
{{ project }}
</md-option>
</md-autocomplete>
这是TypeScript(work-card.component.ts):
import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {Work} from '../../models/work';
import {FormControl} from '@angular/forms';
@Component({
selector: 'wtc-work-card',
templateUrl: './work-card.component.html',
styleUrls: ['./work-card.component.scss']
})
export class WorkCardComponent implements OnInit {
@Input() work: Work;
@Output() workDeleted = new EventEmitter();
projectCtrl: FormControl = new FormControl();
filteredProjects: any;
projects =
[
{
id: 52342,
name: 'Landing Pages'
},
{
id: 1234,
name: 'Maintenance Interface'
}
,
{
id: 52342,
name: 'TYPO3 Website'
}
];
constructor() {
}
ngOnInit() {
this.filteredProjects = this.projectCtrl.valueChanges
.startWith(null)
.map(project => project && typeof project === 'object' ? project.name : project)
.map(name => name ? this.filterProjects(name) : this.projects.slice());
}
filterProjects(val: string) {
return this.projects.filter(project => new RegExp(`^${val}`, 'gi').test(project.name));
}
displayFn(project): string {
console.log(project);
return project ? project.name : project;
}
deleteWork(): void {
this.workDeleted.emit();
}
}
注意:当我删除/注释ngOnInit中的代码时,错误消失了(当然,自动完成功能不起作用)
在module.ts中我正在导入FormControl
和ReactiveFormControl
MdAutocomplete文档:MdAutocomplete
有谁知道这是什么问题? 提前谢谢!
答案 0 :(得分:0)
问题是您应该使用async
pipe 。
this.filteredProjects
是Observable
,因此您必须执行以下操作:
<md-option *ngFor="let project of filteredProjects | async" [value]="project.name">