Reputation: 4972
I am adding the values of a form into an array and then display in the console.
This is my submit button script:
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);
}
When I click on submit, I can properly see the item in the console, but when I want to added on the screen I got a blank div.
Here is the HTML page:
<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>
In the <ul>
nothing is shown.
Here is my full typescript script for the <rb-shopping-list>
template:
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);
}
}
EDIT
The ShoppingServiceList script:
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)
}
}
Upvotes: 0
Views: 509
Reputation: 136
You aren't binding the *ngFor in your template to an array in your component. If the ShoppingListService (sls) has an array of items, you could use that in your template doing something like the following:
<ul class="list-group">
<a class="list-group-item" style="cursor: pointer" *ngFor="let item of sls.getItems()">{{item.name}} | ({{item.amount}})</a>
</ul>
Be careful of the names. The value following the "of" in the *ngFor statement needs to be an array. In the double curly brace interpolation, you want to use the "item" variable that you are using as the looping variable.
Upvotes: 2
Reputation: 41533
You should use an output variable to notify the parent to make the service call again,
In your ShoppingListAddComponent, add a output variable as
Output() countInsert :EventEmitter<number> =new EventEmitter<number>();
add the below lines in your submit method
this.countInsert.emit(i++)
You should handle the change in your parent component as
<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
}
Upvotes: 0