2017-03-17 27 views
0

我将表单的值添加到数组中,然后显示在控制台中。Angular 2的值显示在控制台中,但是当我想在模板中显示角度值时未定义

这是我的提交按钮脚本:

onSubmit(myForm){ 
    console.log(this.myForm.value.name); 
    this.item = [this.myForm.value.name, this.myForm.value.amount]; 
    this.sls.addItem(this.item); 
    console.log(this.item); 
} 

当我点击提交,我可以正确地看到该项目的控制台,但是当我想在屏幕上添加我得到了一个空白格。

下面是HTML页面:

<div class="row"> 
    <div class="col-xs-10"> 
    <rb-shopping-list-add></rb-shopping-list-add> 
    <hr> 
    <ul class="list-group"> 
     <a class="list-group-item" style="cursor: pointer" *ngFor="let item of items">{{items.name}} | ({{items.amount}})</a> 
    </ul> 
    </div> 
</div> 

<ul>什么也看不见了。

下面是<rb-shopping-list>模板,我完全打字稿脚本:

export class ShoppingListAddComponent implements OnInit { 

     isAdd:boolean=true; 
     public item; 
     myForm: FormGroup; 
     constructor(private sls:ShoppingListService, formBuilder: FormBuilder) { 
     this.myForm = formBuilder.group({ 
      'name':['', Validators.required], 
      'amount': ['', Validators.required] 
     }); 
     } 

     ngOnInit() { 
     } 

     onSubmit(myForm){ 
     console.log(this.myForm.value.name); 
     this.item = [this.myForm.value.name, this.myForm.value.amount]; 
     this.sls.addItem(this.item); 
     console.log(this.item); 
     } 

    } 

编辑

的ShoppingServiceList脚本:

import { Ingredient } from "../shared"; 

export class ShoppingListService { 
    private items: Ingredient[] = []; 

    constructor() {} 

    getItems() { 
    return this.items; 
    } 

    addItems(items: Ingredient[]) { 
    Array.prototype.push.apply(this.items, items); 
    } 

    addItem(item: Ingredient){ 
    this.items.push(item) 
    } 
} 
+0

您误解了ngFor语法更改为* ngFor =“让项目条目”> {{items.name}} | ({{items.amount}}) –

+0

您需要遍历ShoppingListService中定义的集合。与此行相同的集合 - > this.sls.addItem(this.item)。发布您的ShoppingListService代码 – Riv

+0

我通过添加ShoppingListService脚本更新了代码人。 – droidnation

回答

2

您尚未绑定*您ngFor模板添加到组件中的数组。如果ShoppingListService(SLS)的项目的数组,你可以使用在你的模板做类似如下:

<ul class="list-group"> 
    <a class="list-group-item" style="cursor: pointer" *ngFor="let item of sls.getItems()">{{item.name}} | ({{item.amount}})</a> 
</ul> 

小心的名字。 * ngFor语句中的“of”后面的值需要是一个数组。在双重大括号内插中,您希望使用您用作循环变量的“item”变量。

+0

谢谢,但它没有奏效。我更新了ShoppingListService的问题,如果你仍然想看看和帮助 – droidnation

0

您应该使用的输出变量通知父母再次使服务调用,

在你ShoppingListAddComponent,添加一个输出变量

Output() countInsert :EventEmitter<number> =new EventEmitter<number>(); 

添加下面的线在你提交方法

this.countInsert.emit(i++) 

您应该处理的

在父组件的变化210
<rb-shopping-list-add (countInsert)="refreshData($event)"></rb-shopping-list-add> 

refreshData(val){ 
//make the service call again to get the new set of data 
} 
相关问题