myList: any;
ngOnInit(){
this.myList = [
{id: 1, name: 'a'},
{id: 2, name: 'b'},
{id: 3, name: 'c'},
{id: 4, name: 'd'},
];
}
在我的HTML中
<input *ngFor="let l of myList" [(ngModel)]="l.name" name="{{l.id}}" />
它的工作情况如下:
Chrome Dev:
然后当我在我的ngOnInit中调用另一个服务时,如下所示:
myList: any;
ngOnInit(){
this.myList = [
{id: 1, name: 'a'},
{id: 2, name: 'b'},
{id: 3, name: 'c'},
{id: 4, name: 'd'},
];
this.outletService.getAll().then(outlets => {
this.outlets = outlets;
});
}
突然间,输入中没有值,如下所示:我的html代码是相同的。
可能发生什么?如何将值显示在输入中?
这是outletService .getAll()
getAll() {
return new Promise(resolve => {
let headers = new Headers({
'Content-Type': 'application/json'
});
let options = new RequestOptions({ headers: headers });
this.http.get(this.host + '/outlets', options)
.subscribe(data => {
resolve(data.json()); //Return array of objects
});
});
}
以下是来自outletService的回复:
控制台中没有错误,我希望来自name
的属性this.myList
,而不是来自outletName
的{{1}}。
更有趣的是:我甚至不需要拨打其他服务: 如果我只是将新数组分配给this.outlets,它就不会起作用,就像这样:
this.outlets
并在html文件中添加另一行。
myList: any;
outlets: any;
ngOnInit(){
this.myList = [
{id: 1, name: 'a'},
{id: 2, name: 'b'},
{id: 3, name: 'c'},
{id: 4, name: 'd'},
];
this.outlets = [
{id: 1, name: 'a'},
{id: 2, name: 'b'},
{id: 3, name: 'c'},
{id: 4, name: 'd'},
];
}
答案 0 :(得分:0)
您应该更改模板。您返回的数据没有name
属性:
<input *ngFor="let l of myList" [(ngModel)]="l.outletName" name="{{l.id}}" />
哦,好吧...... Gunter在评论中已经提到了这一点:)
答案 1 :(得分:0)
实际上,ngModel没有给输入赋值,因为两个对象的id属性是相同的!
如果我改变了:
myList: any;
outlets: any;
ngOnInit(){
this.myList = [
{id: 1, name: 'a'},
{id: 2, name: 'b'},
{id: 3, name: 'c'},
{id: 4, name: 'd'},
];
this.outlets = [
{id: 1, name: 'a'},
{id: 2, name: 'b'},
{id: 3, name: 'c'},
{id: 4, name: 'd'},
];
}
对此:
myList: any;
outlets: any;
ngOnInit(){
this.myList = [
{id: 1, name: 'a'},
{id: 2, name: 'b'},
{id: 3, name: 'c'},
{id: 4, name: 'd'},
];
this.outlets = [
{id: 5, name: 'a'},
{id: 6, name: 'b'},
{id: 7, name: 'c'},
{id: 8, name: 'd'},
];
}
然后它的作品!问我为什么?我不知道..如果有人可以解释会很棒!