首页 > 解决方案 > NgFor 在使用数组创建下拉选择时仅支持绑定到数组等可迭代对象

问题描述

运行应用程序时出现以下错误:

错误错误:找不到类型为“subLandscape”的不同支持对象“[object Object]”。NgFor 仅支持绑定到 Iterables,例如 Arrays。

我在 HTML 中引用的 subLandscape 变量是一个数组,但在将它与“ngFor”一起使用时会引发错误

HTML:

 <div class="form-group" [class.has-error]="subLandscape.invalid && subLandscape.touched">
          <strong>Sub Landscape</strong>
          <br>
          <p>Please choose from one of the Sub Landscape options. Sub Landscape options are for reporting only.</p>
          <label class="control-label">SubLandscape:</label>
          <mat-select #subLandscape="ngModel" type="text" class="form-control"  name="subLandscape" [ngModel]="model.subLandscape">
              <mat-option *ngFor="let item of subLandscape">
                  {{ item }}
              </mat-option>
          </mat-select>
          <div *ngIf="subLandscape.invalid && subLandscape.touched" class="alert alert-danger">
            Select the Sub Landscape from the provided list.
          </div>
 </div>

模型:

export class SModel {
  constructor (
    public description: string,
    public reasons: string,
    public projectName: string,
    public subLandscape: string,
    public centerdata: string,
    public nom: number,
    public size: string,
    public dbgh: string
  ) {

  }
}

零件:

import { Component, OnInit } from '@angular/core';
import { Standalone } from '../standalone';
import { StandaloneModel } from '../models/standalone.model';
import {MatTableModule, MatTableDataSource} from '@angular/material/table';

@Component({
  selector: 'app-standalone-form',
  templateUrl: './standalone-form.component.html',
  styleUrls: ['./standalone-form.component.css']
})
export class StandaloneFormComponent {
  public project: string[] = ['', 'appdev', 'apptest', 'appqa'];
public subLandscape: string[] = ['DEV', 'Testing', 'QA', 'UAT'];
  public dataCenter: string[] = ['PDC', 'SDC'];
public model = new SModel('', '', '', '', '', 0, '', '');

}

标签: arraysangular

解决方案


可能是因为它无法区分subLandscapefrom #subLandscape="ngModel"和组件属性数组public subLandscape: string[] = ['DEV', 'Testing', 'QA', 'UAT'];。改个名字应该可以解决问题


推荐阅读