使用Angular2中的静态对象数组绑定Angular中的“选择”下拉列表
我正在用静态数据绑定Select下拉列表 ProffesionModel.ts使用Angular2中的静态对象数组绑定Angular中的“选择”下拉列表,angular,angular2-forms,angular2-services,Angular,Angular2 Forms,Angular2 Services,我正在用静态数据绑定Select下拉列表 ProffesionModel.ts export interface Proffesion { id : number; title : string; } import { Injectable } from '@angular/core'; import { Proffesion } from "../model/proffessionModel"; @Injectable() export class PeopleServic
export interface Proffesion {
id : number;
title : string;
}
import { Injectable } from '@angular/core';
import { Proffesion } from "../model/proffessionModel";
@Injectable()
export class PeopleService {
proffesions : Proffesion[] = [
{id : 1, title : "Teacher"},
{id : 2, title : "Engineer"},
{id : 3, title : "Doctor"}
];
constructor() { }
getAllProffession() : Proffesion[]{
return this.proffesions;
}
}
app.PeopleListService.ts
export interface Proffesion {
id : number;
title : string;
}
import { Injectable } from '@angular/core';
import { Proffesion } from "../model/proffessionModel";
@Injectable()
export class PeopleService {
proffesions : Proffesion[] = [
{id : 1, title : "Teacher"},
{id : 2, title : "Engineer"},
{id : 3, title : "Doctor"}
];
constructor() { }
getAllProffession() : Proffesion[]{
return this.proffesions;
}
}
app.addperson.ts
import { Component } from "@angular/core";
import { ActivatedRoute, Router } from "@angular/router";
import { Proffesion } from "../model/proffessionModel";
import { PeopleService } from "../services/app.peopleListService";
@Component({
selector: 'add-person',
templateUrl: 'addperson/app.addperson.html'
})
export class AddPersonComponent {
proffesion : Proffesion [];
constructor(private route: ActivatedRoute, private router: Router, private peopleService:PeopleService){
this.proffesion = peopleService.getAllProffession();
}
}
app.addperson.html
<section>
<form (ngSubmit)="savePerson()" #personForm="ngForm">
<div>
<label for="profession">Profession: </label>
<select name="proffesion" [(ngModel)]="person.proffesion" #proffesion="ngModel">
<option *ngFor="let p of proffesion" [value]="p.id">{{p.title}}</option>
</select>
</div>
<div>
<button type="submit" [disabled]="!personForm.form.valid">Save</button>
</div>
</form>
</section>
<button (click)="gotoPeoplesList()">Back to peoples list</button>
职业:
{{p.title}}
拯救
返回人民名单
我的addperson页面加载时出现以下错误
异常:未捕获(承诺中):错误:addperson/app.addperson.html:28:18中的错误由以下原因引起:找不到类型为“proffision”的不同支持对象“[object object]”。NgFor只支持绑定到数组之类的可重用文件
您可以在模板中这样尝试
<select [(ngModel)]="person.proffesion" >
<option *ngFor=" let object of list_object" value="{{object.id}}">
{{object.name}}
</option>
</select>
{{object.name}
也请参考此帖子
问题是您多次使用word
proffision
像arrayName
中的localVariableName
中的绑定一样
可能是因为您在ngModel
中也指定了相同的名称
因此,避免在任何地方使用相同的名称。为什么要在ngMOdel中使用word
Proffision
和arrayName
一样多次使用localVariableName
进行绑定?这不是故意的。我正在学习Angular2,所以不知道确切的命名对话OK NP,尝试使用不同的名称,可能会导致相同的错误,如果没有帮助,请尝试在组件中控制台您的数组OK。我更改localvariableName的名称及其工作方式。:)愚蠢的我am@Vega:为了所需代码的简单性和可读性,我没有在代码中提到这一部分