[英]Angular 2 How to use data I got in the html in component
Hi I am currently having difficulty binding data using Angular2. 嗨,我目前在使用Angular2绑定数据时遇到困难。
I have this data getting from server and I ngFor the data which includes price or certain product. 我有从服务器获取的数据,并且包含有价格或某些产品的数据。
But I also have math algorithm to add an additional fee on the product which means I need to pass the data that has been ngFor to the component so that component can use the data. 但是我也有数学算法来为产品增加额外的费用,这意味着我需要将ngFor的数据传递给组件,以便组件可以使用该数据。
How could I achieve this? 我怎样才能做到这一点?
<div *ngFor="let r of products | keyValues">
<div id="tutor-price"><span id="month">월 8회</span> <span id="price"> {{r.value['charge']}} </span></div>
</div>
I want to pass this 'r.value['charge']' data to component. 我想将此'r.value ['charge']'数据传递给组件。
Thank you! 谢谢!
You should create a new collection of products, one that has the additional property in your component. 您应该创建一个新的产品集合,该集合中的组件具有附加属性。 Iterate over this collection via
ngFor
. 通过
ngFor
遍历此集合。
Here is an example: 这是一个例子:
import {Component} from '@angular/core';
import Product from 'app/models';
import ProductService from 'app/services';
@Component({
// boilerplate and ceremony
})
export class ProductsComponent {
constructor(readonly productService: ProductService) {}
ngOnInit() {
this.productService.getAll().subscribe(products => {
this.products = products.map(product => ({
...product,
charge: calculateCharge(product)
}));
});
}
products: Array<Product & {charge?: number}> = [];
}
function calculateCharge(product: Product) {
return 1; // stub
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.