【问题标题】:I cant populate a select我无法填充选择
【发布时间】:2021-10-03 20:01:32
【问题描述】:

我有数据可以在 Angular 中填充选择,我正在使用我在互联网上看到的示例,但我在 html 上看不到任何内容。未来的数据将来自服务,但我试图首先使用这些编码数据进行测试。 最初,该示例使用 ngModel 进行通信,但这会导致错误。所以我尝试用 formGroup 替换它,但我现在不知道在其中输入什么。

     areas: Area = {
        id: 1,
        nombre: "Contabilidad"
      };
    
     onSelect(id: any): void{
        console.log('id ', id);
      }
    
<form class="theForm" (ngSubmit)="onSubmit()" [formGroup]="myForm">

    <br><br>
    <label >Area </label><br>
          <select [formGroup]="myForm." (change)="onSelect($event.target.value)">
              <option *ngFor="let area of areas" value={{areas.id}}>
                 {{areas.nombre}}
              </option>
    </select>
    <br><br>

错误:

Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

this.form._updateTreeValidity is not a function

来自服务的数据将是 id、names 的集合

【问题讨论】:

  • 您的areas 不是数组。

标签: angular typescript forms select


【解决方案1】:
  1. 作为@Arcteezy sias,areas 不是数组。改为
     areas: Area[] = [
      {
        id: 1,
        nombre: "Contabilidad"
      }
     ];

  1. ng-if 中,您要引用项目(area),而不是整个数组(areas):value={{area.id}}{{area.nombre}}

【讨论】:

    【解决方案2】:

    首先,您的 TypeScript 问题。你的数组定义是错误的。您正在创建 object 而不是 array。所以,你的 areas 数组应该是:

    areas: Area[] = [
        { id: 1, nombre: 'Contabilidad' },
        { id: 2, nombre: 'RRHH' },
        { id: 3, nombre: 'Finanzas' }
    ]
    

    角部分。您正在使用Angular Reactive Forms,请务必先检查一下。 您的标记有误。首先,您应该使用提供的FormGroup/FormBuilder API 创建一个myForm 对象并创建一个nombreArea FormControl:

    ...
    
    import { FormBuilder, Validators } from "@angular/forms";
    
    ...
    
    export class AreaComponent {
    
      constructor(public fb: FormBuilder) { }
    
      ...
    
      myForm = this.fb.group({
        nombreArea: [null]
      });
    
      onSelect(event) {
        console.log(event);
      }
    
    }
    

    也就是说,您的select 必须是FormControl,而不是FormGroup。像这样:

    <select class="area-select" (change)="onSelect($event)" formControlName="nombreArea">
       <option value="" disabled>Seleccionar Area</option>
       <option *ngFor="let area of areas" [ngValue]="area.id">{{area.nombre}}</option>
    </select>
    

    这样,它应该渲染一个带有“默认”选项(选择区域)的select元素,显示area.name并选择area.id作为值

    反应式表单有点冗长,但一旦你掌握了它们,它们就会非常有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-04
      • 1970-01-01
      • 2017-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-07
      相关资源
      最近更新 更多