使用反应形式绑定数组数据

时间:2020-05-21 05:23:25

标签: angular angular-reactive-forms

在学习Angular时,我陷入了一个问题。

我有使用反应性方法的表格。

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

我希望当我选择“模型”时,它应该给我它的“价格”,并且当我验证表单时,我会在console.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);
  }
}

我迷路了。 预先谢谢你:)

2 个答案:

答案 0 :(得分:2)

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

<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('');
    }
  });
}

答案 1 :(得分:0)

我认为[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>