问题
I'm trying to bind viewmodels to a view through component. Initially I did this in the component and it was almost working:
model: any = {
TenantId: '',
CustomFieldName: '',
quantities: []
};
quantity: any = {
price: '',
name: ''
}
Then on button click for adding new object of
model
I was doing this:
addNewQuantity() {
if (this.newQuantity) {
this.quantity.name = this.newQuantity;
this.model.quantity.push(this.quantity);
this.newQuantity = '';
}
}
The issue with above event was that the same quantity object was added for every new click.
What I did next is that I created two models:
Pricegridquantity viewmodel:
export class PriceGridQuantity {
price: string;
name: string;
}
Pricegrid viewmodel
import { PriceGridQuantity } from './pricegridquantity';
export class PriceGridModel {
TenantId: number;
CustomFieldName:string;
PriceList: Array <PriceGridQuantity> ; }
Now I'm trying to link everything in the component, I have this:
model: PriceGridModel[] = [];
Is the statement above correct to initialize a new VM of type PriceGridModel?
If no, please let me know what is better.
And 2nd, on the button click to add new object of type PriceGridQuantity to PriceGridModel, what is the correct way of initializing and then adding object of type PriceGridQuantity to the PricegridModel?
回答1:
The reason for the list of quantities being the same is because you have an object called quantity accessible to the entire view via this declaration:
quantity: any = {
price: '',
name: ''
}
So in a view if you have the ([ngModel])=quantity.name
or ([ngModel])=quantity.price
it will be bound to the values in quantity. This is problematic because you are setting the value quantity.name
in the addNewQuantity function.
addNewQuantity() {
if (this.newQuantity) {
this.quantity.name = this.newQuantity;
this.model.quantity.push(this.quantity);
this.newQuantity = '';
}
}
So any template that is set with ([ngModel])=quantity.name
will now have the value set in the previous function.
A better implementation is to have a newQuantityObject
and an object that has an array property that stores each newly added quantity. Then you don't need any new classes to implement. For example:
newQuantity = {
price: '',
name: ''
};
model: any = {
TenantId: '',
CustomFieldName: '',
quantities: []
};
addNewQuantity() {
if (this.newQuantity.price !== '' && this.newQuantity.name !== '') {
this.model.quantities.push(this.newQuantity);
newQuantity = {
price: '',
name: ''
};
}
}
Then you could display the list of quantity objects in a view like this:
<div *ngFor="let quantity of model.quantities; let i=index;" >
<input type="text" value="{{quantity.name}}" [(ngModel)]="model.quantities[i].name" />
<input type="text" value="{{quantity.price}}" [(ngModel)]="model.quantities[i].price" />
</div>
来源:https://stackoverflow.com/questions/57826569/angular-viewmodels-and-usage-in-components