将数组数据与响应式表单绑定



在学习Angular时,我遇到了一个问题。

我有一个使用反应式方法的表单。

我有一个数组"模型",其中包含每个"模型"的"价格">

我希望当我选择"模型"时,它应该给我它的"价格",当我验证表单时,我在控制台中收到所选模型及其价格.log (this.form.value(

这是我的 HTML:

<form [formGroup]="factureForm" (ngSubmit)="onSubmitForm()">
<select formControlName="model">
<option *ngFor="let model of models">{{ model.model }}</option>
</select>
<select formControlName="price">
<option *ngFor="let model of models">{{ model.price }}</option>
</select>
<button type="submit">Submit</button>
</form>

这是我的 TS :

import { Component, OnInit } from "@angular/core";
import { FormsModule, FormGroup, FormBuilder } from "@angular/forms";
@Component({
selector: "app-relational-data",
templateUrl: "./relational-data.component.html",
styleUrls: ["./relational-data.component.css"],
})
export class RelationalDataComponent implements OnInit {
factureForm: FormGroup;
models = [
{
model: "Model 1",
price: 20,
},
{
model: "Model 2",
price: 50,
},
];
constructor(private formBuilder: FormBuilder) {}
ngOnInit() {
this.initFactureForm();
}
initFactureForm() {
this.factureForm = this.formBuilder.group({
model: [""],
price: [""],
});
}
onSubmitForm() {
const newFacture = this.factureForm.value;
console.log(newFacture);
}
}

我迷路了。 提前谢谢你:)

由于您需要更改模型时更改价格,因此可能需要在模型更改时设置价格。而且您也不需要价格下拉菜单,因为它取决于型号。

<form [formGroup]="factureForm" (ngSubmit)="onSubmitForm()">
<select formControlName="model">
<option value=''>Select</option>
<option *ngFor="let model of models">{{model.model}}</option>
</select>
<input type="text" formControlName="price">
<button type="submit">Submit</button>
</form>
initFactureForm() {
this.factureForm = this.formBuilder.group({
model: [""],
price: [""],
});
// Look for changes to the model form-control
this.factureForm.get('model').valueChanges.subscribe(newValue => {
// newValue will be holding the 'model' attribute of the selected model
// Searching the models array for the item with the selected model name
const selectedModel = this.models.find(item => item.model === newValue);
// If the item is found in the array,
// then set the price of the model item to the price form-control.
// If not found, set price to ''
if (selectedModel) {
this.factureForm.get('price').setValue(selectedModel.price);
} else {
this.factureForm.get('price').setValue('');
}
});
}

我认为[ngValue]缺失了。

<form [formGroup]="factureForm" (ngSubmit)="onSubmitForm()">
<select formControlName="model">
<option *ngFor="let model of models" [ngValue]="model.model">{{ model.model }}</option>
</select>
<select formControlName="price">
<option *ngFor="let model of models" [ngValue]="model.price">{{ model.price }}</option>
</select>
<button type="submit">Submit</button>
</form>

最新更新