(编辑 Angular 5)我无法获取 NgModel 中对象的值
(Editing Angular 5) I can't get the values of the object that is in NgModel
无法获取该字段的对象
component.html
<div class="form-group">
<input type="number" name="totalPrice" class="form-control" #lastname="ngModel"[(ngModel)]="invoiceService.selectedInvoice.totalPrice" readonly>
</div> <!-- working ok -->
<div class="form-group">
<input type="number" name="purchases" class="form-control" #purchases="ngModel" [(ngModel)]="invoiceService.selectedInvoice.purchases['product']" readonly>
</div><!-- not working -->
这个元素
有什么想法吗?
这里有一个例子(login => user:user@user.com | pass: user123)
StackBlitz
希望我已经正确理解了你的问题。
对于这部分 invoiceService.selectedInvoice.purchases['product']
,您正在尝试访问数组条目之一,我认为这些条目属于 product
类型。
要访问 purchases
数组的每个条目,您需要对每个数组条目执行类似的操作,但不推荐这样做:
[(ngModel)]="invoiceService.selectedInvoice.purchases[0]" // get the first product (first entry of the array), etc.
但是索引会被硬编码,这正如我所说的不推荐。
因此您应该执行以下操作:
<div class="form-group" *ngFor="let product of invoiceService.selectedInvoice.purchases">
<!-- Creates an input field for every product's price -->
<input type="number" name="price" class="form-control" [(ngModel)]="product.price" readonly>
<!-- Print the product object as json -->
{{prodcut | json}}
</div>
如果您不熟悉 *ngFor
,请参阅 here。
最后这就是解决方案。它不起作用,因为我使用两种方式绑定 NgModel,它将传入值绑定到同一个变量 - i.product.name
<ng-template ngFor let-i [ngForOf]="invoiceService.selectedInvoice.purchases">
{{i.product.name | json}}
<input type="text" name="purchases" class="form-control" [value]="i.product.name" readonly>
</ng-template>
无法获取该字段的对象
component.html
<div class="form-group">
<input type="number" name="totalPrice" class="form-control" #lastname="ngModel"[(ngModel)]="invoiceService.selectedInvoice.totalPrice" readonly>
</div> <!-- working ok -->
<div class="form-group">
<input type="number" name="purchases" class="form-control" #purchases="ngModel" [(ngModel)]="invoiceService.selectedInvoice.purchases['product']" readonly>
</div><!-- not working -->
这个元素
有什么想法吗?
这里有一个例子(login => user:user@user.com | pass: user123)
StackBlitz
希望我已经正确理解了你的问题。
对于这部分 invoiceService.selectedInvoice.purchases['product']
,您正在尝试访问数组条目之一,我认为这些条目属于 product
类型。
要访问 purchases
数组的每个条目,您需要对每个数组条目执行类似的操作,但不推荐这样做:
[(ngModel)]="invoiceService.selectedInvoice.purchases[0]" // get the first product (first entry of the array), etc.
但是索引会被硬编码,这正如我所说的不推荐。
因此您应该执行以下操作:
<div class="form-group" *ngFor="let product of invoiceService.selectedInvoice.purchases">
<!-- Creates an input field for every product's price -->
<input type="number" name="price" class="form-control" [(ngModel)]="product.price" readonly>
<!-- Print the product object as json -->
{{prodcut | json}}
</div>
如果您不熟悉 *ngFor
,请参阅 here。
最后这就是解决方案。它不起作用,因为我使用两种方式绑定 NgModel,它将传入值绑定到同一个变量 - i.product.name
<ng-template ngFor let-i [ngForOf]="invoiceService.selectedInvoice.purchases">
{{i.product.name | json}}
<input type="text" name="purchases" class="form-control" [value]="i.product.name" readonly>
</ng-template>