Angular中使用ng-repeat渲染下拉列表无法获取数据报错如何解决
错误原因
你混淆了不同版本Angular的循环指令语法:ng-repeat是AngularJS(1.x旧版本)的专属循环语法,不适用于Angular 2及以上的新版本。
由于框架无法识别ng-repeat语法,你声明的临时循环变量x不会被正常解析,因此会抛出Property 'x' does not exist on type 'AppComponent'的报错。
修复方案
仅需将模板中的ng-repeat替换为Angular 2+对应的*ngFor语法即可,修正后的代码如下:
app.component.html
<h1>hi </h1> <br><br><br> <select> <option *ngFor="let x of names">{{x}}</option> </select>
可选优化(绑定下拉选中值)
如果需要双向绑定下拉框的选中结果,可以按如下方式修改:
- 在
app.component.ts中新增用于存储选中值的属性:
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { names = ["Pending", "Out for delivery", "Delivered"]; selectedStatus = ""; // 新增选中值存储变量 title = 'dropdownproj'; }
- 调整模板代码,添加双向绑定逻辑:
<select [(ngModel)]="selectedStatus"> <option *ngFor="let x of names" [value]="x">{{x}}</option> </select>
内容的提问来源于stack exchange,提问作者mordor619
相关产品推荐
相关产品推荐

