我正在创建一个反应式表单数组来实现 CRUD 操作。经过长时间的谷歌搜索,我发现有几种方法可以实现这一点。我的疑问是:
- 如何使用货币接口从表单制作数据模型?
- 如何在单击按钮( addItem() )时将项目添加到 Items 数组?
提交后,是否可以将模型导出为 JSON?
货币.interface.ts
export interface Currency {
name: string;
date: string;
address: string;
remarks: string;
serialNumber: number;
idNumber: number;
phoneNumber: number;
mobileNumber: number;
nationality: string;
totalCost: number;
tax: number;
taxTotal: number;
grandTotal: number;
items: Item[];
}
export interface Item {
currencyName: string;
currencyType: string;
currencyValue:string;
total: number;
presentRate:number;
}
货币.component.ts
ngOnInit() {
this.currencyType = ['CN & Coins']
this.myForm = this.fb.group({
name: ['', [Validators.required, Validators.minLength(2)]],
date: ['', [Validators.required, Validators.minLength(2)]],
address: ['', [Validators.required, Validators.minLength(2)]],
remarks: ['', [Validators.required, Validators.minLength(2)]],
serialNumber: ['', [Validators.required, Validators.minLength(1)]],
idNumber: ['', [Validators.required, Validators.minLength(2)]],
phoneNumber: ['', [Validators.required, Validators.minLength(2)]],
mobileNumber: ['', [Validators.required, Validators.minLength(2)]],
nationality: [''],
tax: ['', [Validators.minLength(2)]],
totalCost: [{ value: '', disabled: true }, [Validators.minLength(2)]],
taxAmount: [{ value: '', disabled: true }, [Validators.minLength(2)]],
grandTotal: [{ value: '', disabled: true }, [Validators.minLength(2)]],
items: this.fb.array([
this.initItem(),
])
});
}
initItem() {
return this.fb.group({
currency: [''],
currencyName: [''],
currencyType: [''],
amount: [],
presentRate:[''],
total:[{ value: '', disabled: true }, [Validators.minLength(2)]]
});
}
货币.component.html
<div class="flex-item" fxFlex="50%">
<md-card class="app-input-section" style="height: relative" >
<md2-datepicker formControlName="date"></md2-datepicker>
<div formArrayName="items">
<div let i=index>
<div [formGroupName]="i">
<md2-autocomplete [items]="currency"
item-text="currency"
(change)="handleChange($event, i)"
placeholder="Currency purchased"
formControlName="currency"
>
</md2-autocomplete>
<md-select placeholder="Currency type" formControlName="currencyType">
<md-option *ngFor="let type of currencyType" [value]="type" >
{{type}}
</md-option>
</md-select>
<md-input-container >
<input mdInput placeholder="Amount" formControlName="amount">
</md-input-container>
<md-input-container >
<input mdInput placeholder="Present rate" [value]="presentRate" formControlName="presentRate" >
</md-input-container>
<md-input-container >
<input mdInput placeholder="Rupee Equivalent" value={{getRupee()}} formControlName="total" >
</md-input-container>
</div>
<div class="flex-item" fxFlex >
<button md-raised-button color="primary" type="submit" >Save</button >
<button md-raised-button color="primary" (click)="addItem()">Add</button>
<button md-raised-button color="warn">Remove selected currency</button>
<button md-raised-button >Edit</button>
</div>
</div>
</div>
</md-card>
</div>