Angular: * ngFor l oop выдает ошибку: не удается найти другой поддерживающий объект '[object Object]' типа 'object' - PullRequest
0 голосов
/ 05 марта 2020

Постановка проблемы

Когда я использую *ngFor в HTML, выдается ошибка: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays., хотя я использую массив в *ngFor l oop.


Код

HTML Я использую Angular Материал 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 l oop должен перебирать элементы без проблем и без ошибок. Признавая, что он выполняет итерацию по массиву.


Фактические результаты

*ngFor l oop не распознает массив techSkills, насколько я может сказать и, следовательно, не в состоянии перебрать его.

1 Ответ

1 голос
/ 05 марта 2020

Сам по себе следующий код совершенно действителен:

<mat-chip-list>
    <mat-chip *ngFor="let techSkill of techSkills">
        content
    </mat-chip>
</mat-chip-list>

Разница в том, что список микросхем доступен в качестве ссылки #techSkills:

<mat-chip-list #techSkills> <!-- here -->
    <mat-chip *ngFor="let techSkill of techSkills">
        content
    </mat-chip>
</mat-chip-list>

В этом объеме techSkills теперь объект, указывающий на список микросхем, а не на массив, который вы ожидаете. Массив все еще существует, но он затенен #techSkills.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...