I want to bind ViewModel
in Angular 8
Component
name "Test". I initialize the Viewmodel
as null
. It works fine with model but not with ViewModel
.
here is link Code editor link:
https://stackblitz.com/edit/angular-a95o1e
Model # 1
export class GoldDetail
{
//For Gold
GoldDetailId: number;
PurchaseNo: number;
SaleNo: number;
Weight: number;
}
Model # 2
export class CurrencyDetail {
Name :string;
CurrencyId:number;
Amount:number;
}
i add view model like this
export class Vmmodel
{
goldDetail :GoldDetail;
currencyDetail:CurrencyDetail;
}
i want to bind this "VmModel" to in my component. i initialize viewmodel with null.eg test.ts
resetForm(form? : NgForm): any {
if(form!=null)
form.reset();
this.paymentService.vmmodel ={
currencyDetail:new CurrencyDetail(),
goldDetail:new GoldDetail(),
}
}
test.html
<form autocomplete="off" #golddetail="ngForm" (submit)="onSubmit(golddetail)" >
<div class="form-group col" >
<label>weight</label>
<input #currencyDetail.Name="ngModel" [(ngModel)]="paymentService.vmmodel.currencyDetail.Name" class="form-control">
</div>
</form>
but i got error in console . see attachment pelase see this picture
Thanks in advance i try my best to explain my prblem.
There are a lot of convention problems here, but let's stick on the main question.
You are using vmmodel
before it is initialized.
<input #currencyDetail.Name="ngModel" [(ngModel)]="paymentService.vmmodel.currencyDetail.Name" class="form-control">
Only on reset you do initialize a value to it. What your code is trying to do is access paymentService.vmmodel.currencyDetail.Name
. In other word it cannot read the value of ...vmmodel.currencyDetail
because vmmodel is undefined
.
When the form is "created", the input
is filled with whatever value there is in the ngModel
.
You could intilialize the variable with default values or use the coalease operator.
Noneless you should create a minimal reproductible of your problem so we can start from somewhere.
export class AppComponent {
name = 'Angular';
vmmodel = new Vmmodel(); // as simple as that. This is still going to have problems as inner properties are not initialized neither and paymentService is undefined as well.
resetForm(form? : NgForm): any {
if(form!=null)
form.reset();
this.vmmodel ={
currencyDetail:new CurrencyDetail(),
goldDetail:new GoldDetail(),
// AcBankAccountHolders:null
}
}
}