Angular 2模型绑定(对象数组)

时间:2017-08-31 03:59:30

标签: angular

我是Angular2的新手...我的问题很简单:我想绑定一个Object数组,如下所示:

我有以下组件(app.ts)和视图(cart.html):

(app.ts)档案:

@Component({
selector: 'my-app',
templateUrl: '../Partials/cart.html',
styleUrls: ['../Partials/cart.css']
}) export class AppComponent{

constructor(private http: Http) { };
title = 'ASP.NET MVC 5 with Angular 2';
private headers = new Headers({ 'Content-Type': 'application/json' });

invoice: Invoice = {       

    customer: {
        CustomerName: "Lorem Ipsum",
        Address: "102/102 East Hills Road",
        Suburb: "East Hills",
        State: "NT",
        PostCode: "3563"            
    },
    products: [
        {
            id: "1",
            desc: "Mig Mac",
            unit_price: 8.5,
            quantity: 5
        },
        {
            id: "2",
            desc: "Fillet O Fish",
            unit_price: 4.50,
            quantity: 3
        },
        {
            id: "3",
            desc: "Icecreme",
            unit_price: 0.5,
            quantity: 10
        }

    ]

}

invoice2: Invoice;


getTotal = function () {

    var total = 0;
    for (var i = 0; i < this.invoice.products.length; i++)
    {
        total += this.invoice.products[i].unit_price * this.invoice.products[i].quantity;
    }
    return total;
}


onSubmit() {

    this.create().then(i => {
        this.invoice2 = i;
        console.log(this.invoice2);
    });
}
create(): Promise<Invoice> {
    console.log("POST");
    let url = "/Invoice/Create";
    return this.http.post(url, this.invoice).toPromise()
        .then(res => { return res.json() as Invoice });

}

}; 

export class Invoice {
customer: Customer;
products: Item[];
}

export class Customer {
CustomerName: String;
Address: String;
Suburb: String;
State: String;
PostCode: String;

} 

export class Item {
id: String;
desc: String;
unit_price: Number;
quantity: Number;
}

(cart.html)文件:

<form #f="ngForm" (ngSubmit)="onSubmit()">

<div class="invoice-wrap">

    <div class="invoice-header">

        <div class="container-fluid">

            <div class="row">

                <div class="col-xs-6 col-xxs-12">
                    <div class="customer-details">

                        <p><strong>Invoice To</strong></p>
                        <input type="text" [(ngModel)]="invoice.customer.CustomerName" name="CustomerName" />

                        <span><strong>Address: </strong></span><br />

                        <input type="text" [(ngModel)]="invoice.customer.Address" name="Address" /><br />
                        <input type="text" [(ngModel)]="invoice.customer.Suburb" name="Suburb" /><br />
                        <input type="text" [(ngModel)]="invoice.customer.State" name="State" /><br />
                        <input type="text" [(ngModel)]="invoice.customer.PostCode" name="PostCode" /><br />                          

                    </div>


                </div>
                <div class="col-xs-6 col-xxs-12">
                    <button type="submit" [disabled]="!f.valid">Submit</button>
                </div>

                <div class="clearfix"></div>
            </div>
        </div>

    </div>
</div>



<div class="item-header-wrap">

    <div class="item-header hidden-xs">

        <div class="container-fluid">

            <div class="row">

                <div class="col-sm-2 col-xs-4">

                    <p>Product</p>

                </div>
                <div class="col-sm-3 col-xs-8">
                    <p>Description</p>

                </div>

                <div class="col-sm-2 col-xs-12">
                    <p>Delivery</p>

                </div>

                <div class="col-sm-2 col-xs-12">
                    <p>Click&amp;Collect</p>


                </div>

                <div class="col-sm-1 col-xs-6">
                    <p>Unit Price</p>


                </div>

                <div class="col-sm-1 col-xs-6">
                    <p>Quantity</p>

                </div>

                <div class="col-sm-1 col-xs-12">
                    <p>Line Total</p>

                </div>



            </div>
        </div>
    </div>
</div>





<div class="item-wrap">

    <div class="item" *ngFor="let product of invoice.products">

        <div class="container-fluid">

            <div class="row">

                <div class="col-sm-2 col-xs-4">
                    <div class="azure col">


                        <img src="./images/item.jpg" class="item-img" />

                    </div>

                </div>
                <div class="col-sm-3 col-xs-8">
                    <div class="orange col">

                        <input type="text" [(ngModel)]="product.desc" name="product.desc" value="" />


                    </div>

                </div>

                <div class="col-sm-2 col-xs-12">
                    <div class="azure col">

                    </div>

                </div>

                <div class="col-sm-2 col-xs-12">
                    <div class="click-and-collect col">


                    </div>


                </div>

                <div class="col-sm-1 col-xs-6">
                    <div class="red col">

                        <input type="text" [(ngModel)]="product.unit_price" name="product.unit_price" value="" />

                    </div>


                </div>

                <div class="col-sm-1 col-xs-6">
                    <div class="col">
                        <input type="text" [(ngModel)]="product.quantity" name="product.quantity" value="" />

                    </div>


                </div>

                <div class="col-sm-1 col-xs-12">
                    <div class="red col">
                        <p>${{product.unit_price * product.quantity}}</p>
                    </div>


                </div>



            </div>
        </div>
    </div>






</div>

<div class="total">
    Total = {{getTotal()}}
</div>

我在浏览器中获得以下内容:我的模型填充了对象数组中的最后一个元素。 enter image description here 客户发票对象的一部分已正确绑定,但对象的products数组未正确绑定。我做错了什么?我在谷歌广泛搜索并尝试了各种方法,但似乎没有任何工作。请帮忙。

3 个答案:

答案 0 :(得分:2)

在ngFor循环中创建多个ngModel控件时,请确保为每个控件指定唯一名称:

您可以像这样更改代码

<div class="item" *ngFor="let product of invoice.products;let i=index">

和每个输入字段应更改为

<input type="text" name="name-{{i}}" [(ngModel)]="your binding variable">

希望这有帮助

答案 1 :(得分:0)

您需要在此处使用 ngFor

<div class="item" *ngFor="let product of invoice.products;let i=index">
    <input type="text" name="name-{{i}}" [(ngModel)]="product.invoice.customer.Address">

答案 2 :(得分:0)

你的问题在这里:

<input type="text" [(ngModel)]="product.desc" name="product.desc" value="" />

由于您的HTML代码位于表单中,因此您必须为每个元素使用唯一的名称(输入)。但是你可能忘了使用字符串插值,因此你会得到以下结果: Actual DOM reflect 所有元素都引用简单相同的表单属性:product.desc 在名称中使用字符串插值将解决您的问题:

<input type="text" [(ngModel)]="product.desc" name="{{product.desc}}" value="" />

您应该在使用ngModel的任何地方执行此操作。 此外,正如另一个答案所示,您最好在名称中添加唯一标识符(例如使用带有&#39; - {{i}}&#39;)的索引,以避免与包含多个项目的发票重复同名。