这是我的代码: -
<form>
<div class="col-md-4">
<input type="text" [(ngModel)]="quantity.quantity" name="quantity" class="form-control" placeholder="Quantity">
</div>
<div class="col-md-4">
<input type="text" [(ngModel)]="size.size" name="size" class="form-control" placeholder="Size">
</div>
<div class="col-md-4">
<input type="text" [(ngModel)]="brand.brand" name="brand" class="form-control" placeholder="Brand">
</div>
这是我在角度4中制作数组的模型文件: -
export class BoQuotes {
note: string;
city: string;
name: string;
email: string;
phone_number: string;
message: string
userId: string;
quotes: Array<BoQuote> = new Array<BoQuote>();
}
export class BoQuote {
brand: string = "";
size: string = "";
quantity: string = "";
}
这是我的组成部分: -
addItem() {
var retrievedData = localStorage.getItem("userId");
var loggdinUser = JSON.parse(retrievedData);
this.item.userId = loggdinUser[0]._id;
this.item.quotes.push(this.quantity);
this.item.quotes.push(this.brand);
this.item.quotes.push(this.size);
U.log("Item to be add : " + JSON.stringify(this.item));
if (!this.item.userId) {
return;
}
// let isValid = $('#form').parsley().isValid();
// if (isValid) {
this.quotesService.addItem(this.item).subscribe(
data => {
U.log("Success:-" + JSON.stringify(data));
window.location.reload();
},
err => {
U.log("err1 : " + JSON.stringify(err));
// this.router.navigateByUrl('/dashboard')
}
);
//}
}
需要这种类型的jason数组来保存在db |: -
中[
{
"size": "25 mm",
"quantity": "20",
"price": "111111",
"brand": "tvs"
},
{
"size": "24 mm",
"quantity": "10",
"price": "22222",
"brand": "atlash"
},
{
"size": "35 mm",
"quantity": "30",
"price": "3333",
"brand": "hp"
}
]
答案 0 :(得分:1)
嗨决赛我用反应形式FormArray,FormGroup
解决了我的问题以下是代码:
创建Form qouteForm:FormGroup;
的对象组件文件:
private initForm() {
let note = '';
let city = '';
let name = '';
let email = '';
let phone_number = '';
let message = '';
let userId = '';
let quotesArr = new FormArray([]);
this.qouteForm = new FormGroup({
'note': new FormControl(note, Validators.required),
'city': new FormControl(city, Validators.required),
'name': new FormControl(name, Validators.required),
'email': new FormControl(email, Validators.required),
'phone_number': new FormControl(phone_number, Validators.required),
'message': new FormControl(message, Validators.required),
'userId': new FormControl(userId, Validators.required),
'quotes': quotesArr
});
}
onAddRow() {
(<FormArray>this.qouteForm.get('quotes')).push(
new FormGroup({
'quantity': new FormControl(null, Validators.required),
'size': new FormControl(null, Validators.required),
'brand': new FormControl(null, Validators.required)
})
);
}
模型文件:
export class BoQuotes {
note: string;
city: string;
name: string;
email: string;
phone_number: string;
message: string
userId: string;
quotes: BoQuote[];
}
export class BoQuote {
constructor(public brand: string, public size: string, public quantity: string) { }
}