【发布时间】:2020-06-18 05:01:40
【问题描述】:
问题陈述
当我在 HTML 中使用 *ngFor 时,它会抛出错误:Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.,即使我在 *ngFor 循环中使用了一个数组。
代码
HTML我正在使用 Angular Material 的 mat-chips,而在垫芯片内部我正在使用 *ngFor,这就是错误所在。
<mat-form-field class="techSkillsContain" appearance="outline">
<mat-label>Type in a technical skill</mat-label>
<input matInput placeholder="i.e Java" type="text" maxlength="40" [matChipInputFor]="techSkills"
(matChipInputTokenEnd)="addTechSkill($event)">
<mat-hint>Press enter after you type</mat-hint>
</mat-form-field>
<br><br>
<mat-chip-list #techSkills>
<mat-chip [removable]="true" *ngFor="let techSkill of techSkills" // <== Error HERE
(removed)="removeSkill(techSkill)">
{{techSkill}}
<mat-icon matChipRemove>cancel</mat-icon>
</mat-chip>
</mat-chip-list>
TypeScript
这是我的 techSkills 数组所在的组件。错误是说它不是数组,即使它是。
import { Component, OnInit } from '@angular/core';
import { MatChipInputEvent } from '@angular/material/chips';
@Component({
selector: 'app-account-sign-up',
templateUrl: './account-sign-up.component.html',
styleUrls: ['./account-sign-up.component.scss']
})
export class AccountSignUpComponent implements OnInit {
private techSkills: String[] = []; // <== The console says this is not an array, even though it is...
private softSkills: String[] = [];
constructor() { }
ngOnInit(): void {
}
removeSkill(skill: String): void {
// If the skill is a tech skill, then it will remove it from the tech skill array
if (this.techSkills.indexOf(skill) === this.techSkills.indexOf(skill)) {
const index = this.techSkills.indexOf(skill);
if (index >= 0) {
this.techSkills.splice(index, 1);
}
// If the skill is a soft skill, then it will remove it from the soft skill array
} else {
const index = this.softSkills.indexOf(skill);
if (index >= 0) {
this.softSkills.splice(index, 1);
}
}
}
addTechSkill(event: MatChipInputEvent): void {
const input = event.input;
const value = event.value;
// Add our skill to the tech skills
if ((value || '').trim()) {
this.techSkills.push(value.trim());
}
// Reset the input value
if (input) {
input.value = '';
}
}
addSoftSkill(event: MatChipInputEvent): void {
const input = event.input;
const value = event.value;
// Add our skill to the tech skills
if ((value || '').trim()) {
this.softSkills.push(value.trim());
}
// Reset the input value
if (input) {
input.value = '';
}
}
}
这里到底发生了什么?我一定是忽略了一些小东西。我是否因为看到一个数组而失去理智,但控制台说它不是数组?请帮帮我。
预期结果
*ngFor 循环应该毫无问题且无错误地遍历元素。认识到它正在遍历一个数组。
实际结果
据我所知,*ngFor 循环无法识别 techSkills 数组,因此无法遍历它。
【问题讨论】:
-
确保
techSkills是一个数组。 -
@Caramiriel 啊哈。可能是,让我尝试修复它...
-
@Caramiriel 你修好了!谢谢!请发布您的答案,以便我可以给您代表。
标签: arrays angular typescript loops angular-material