【问题标题】:Expression has changed after it was checked. Previous value: 'model: 1777'. Current value: 'model: 2222'检查后表达式已更改。以前的值:“型号:1777”。当前值:'型号:2222'
【发布时间】:2018-03-16 11:16:29
【问题描述】:

我有这段 html 代码,在这段代码中,我使用 [(ngModel)] 更改我的值输入,当我更改时,我想自动计算我的总计、小计和支付金额。 也许这不是一个好的解决方案,因为我有一些问题。

  1. 当我添加一些数据时,我的所有数据变化值,都得到最后一个设置值。 就像照片中一样,

我需要帮助。

我的html代码

 <form [formGroup]="addsale" (ngSubmit)="onaddsale()">
      <table align="center" class="table table-bordered table-hover">
        <thead>
          <tr style="color:black;">
            <th>Unit_price</th>
            <th>Quantity</th>
            <th>Description</th>
            <th>Subtotal</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          <tr class="group" style="cursor: pointer" *ngFor="let item of products; let i = index">
             <td>
              <input formControlName="Unit_price" id="Unit_price " type="number" class="validate"[(ngModel)]="item.Unit_price">
            </td>
            <td>
              <input formControlName="Quantity" id="Quantity " type="number" class="validate"  [(ngModel)]="item.Quantity"> 
            </td>
            <td>
              <input type="text" formControlName="Description" id="Description" name="Description" [(ngModel)]="item.Description">
            </td>
            <td>
              <input formControlName="Subtotal" id="Subtotal" type="number" class="validate"  [(ngModel)]="item.Subtotal">
            </td>
            <td>
              <button type="button" class="fa" (click)="onDelete(i)">x</button>
            </td>
          </tr>
        </tbody>
      </table>
      <br>
      <br>
      <div class="row">
        <div class="input-field col s2" style="float: right;">
          <label for="total">Total {{total}} ALL</label>
          <input formControlName="total" id="total" type="text" class="validate"   [(ngModel)]="total">
        </div>
        <div class="input-field col s2" style="float: right;">
          <label for="amount_paid">Amount Paid:</label>
          <input formControlName="amount_paid" id="amount_paid" [(ngModel)]="total" type="text" class="validate">
        </div>
        <div class="input-field col s2" style="float: right;">
          <label for="total">Subtotal</label>
          <input formControlName="Subtotal" id="Subtotal" type="text" class="validate"  [(ngModel)]="total">
        </div>
      </div>

      <hr>
      <br>
      <div id="add_homebox_button_container" class="row" style="float: right;">
        <button id="add_client_button" type="submit" class="btn waves-effect waves-light">
          Register
        </button>
      </div>
    </form>

代码ts:

export class AddSaleFormComponent implements OnInit {
  addsale: FormGroup;
  loading: boolean = false;
  client: Client[];
  producttype: ProductType[];
  contrat: Contrat[];
  gpss: GPS[];
  homeboxp: HomeboxP[];
  sensors: Sensors[];
  homebox: Homebox[];
  products: Products[] = [];
  Price: number = 0;
  Total;
  variable: any;
  Quantity: number;
  Unit_price: number;

  selectedClient: Client = new Client('');
  @Input() selectedProduct: Products;

  constructor(
    private router: Router,
    private fb: FormBuilder,
    private ss: SalesService,
    private ps: ProductsService,
    private cs: ClientService,
    private pts: ProducttypeService,
    private css: ContratService,
    private gps: GpsService,
    private hbp: HomeboxpackageService,
    private sensor: SensorsService,
    private hb: HomeboxService

  ) {
    this.addsale = this.fb.group({
      'invoice_number': new FormControl('', [Validators.required, Validators.nullValidator]),
      'invoice_date': new FormControl('', Validators.required),
      'client_id': new FormControl('', Validators.required),
      'amount_paid': new FormControl('', Validators.required),
      'notes': new FormControl('', Validators.required),
      'Subtotal': new FormControl('', Validators.required),
      'products': this.fb.array([]),
      'total': new FormControl('', Validators.required),
      'contactNo': new FormControl('', Validators.required),
      'address': new FormControl('', Validators.required),
      'Unit_price': new FormControl('', Validators.required),
      'Quantity': new FormControl('', Validators.required),
      'Description': new FormControl('', Validators.required),
      'line_num': new FormControl('', Validators.required)
    });
  }

  ngOnInit() {

    this.products = this.ps.getProduct();
    console.log(this.products)

    this.pts.getAllProductType().subscribe(
      producttype => {
        this.producttype = producttype;
      }
    );
  }


  onaddsale() {
    this.loading = true;
    let sale = this.addsale.value
    sale.products = this.products

    let newSale = new Sale(sale);
    console.log(newSale)

    this.ss.saleitemcreate(newSale).subscribe(
      result => {
        if (result === true) {
          Materialize.toast('Sale saved successfully', 4000);
        } else {
          this.loading = false;
        }
      },
      error => {
        this.loading = false;
      }
    );
  }

  get total() {
    let Total = 0;
    for (let p of this.products) {
      Total += p.Unit_price * p.Quantity;
    }
    return Total;
  }
  Subtotal() {
    let subtotal = 0;
    for (let p of this.products) {
      subtotal = p.Unit_price * p.Quantity;
    }
    console.log(subtotal)
    return subtotal;
  }

}

【问题讨论】:

  • 我们需要组件的代码。似乎您在更改检测后更改了属性的值,这并不好。此外,如果您使用ngModel,则不应使用[value],因为ngModel 已在其指向的数据更改时更新表单字段。
  • @OscarPaz 请如何更改我的代码?我编辑我的帖子。谢谢
  • 另外,我改变了[value],没有任何改变
  • @OscarPaz 你能帮忙吗?
  • 当你说'当我添加一些数据'时,你是什么意思?添加新行?可以添加行吗?

标签: angular forms typescript


【解决方案1】:

您的问题是FormGroup。如您所见,您有一个FormControl 用于“Unit_price”。但是,在您的模板中,您有几行,并且在每一行中都有一个指向同一 FormControl 的输入(通过 FormControlName 指令)。但是它们都属于同一个FormGroup,这与表单混淆,因此所有具有相同名称的输入都引用相同的FormControl,从而导致您遇到奇怪的行为。在同一 FormGroup 指令下不能有重复的控件。

您要做的是为表格的每一行定义一个FormGroup。这样,您将拥有一个 FormGroup 数组。在他们每个人中,都会有一个具有唯一名称的FormControl,这样您的问题就会消失。

这意味着您必须为products 数组中的每个产品创建一个FormGroup,并且可能为公共控件(总计、小计...)创建一个不同的FormGroup

当然,这意味着FormGroup 中的products 数组不再是必需的。

另一个建议是从“总计”字段中删除数据绑定,因为您不会对其进行编辑。您可以为他们将 [(ngModel)] 更改为 [ngModel]。

事实上,虽然我不是响应式表单方面的专家,但我认为,如果您使用 FormControl 和 FormGroup,则根本不需要 ngModel

【讨论】:

  • 是的,我明白了,但是这个问题只有在我使用 [(ngModel)] 时才会出现。当我使用 [value] 时这是正常的,但是在这里我想更改我的值,例如,我想更改数量,此时我的总计和小计将自动更改。感谢您的评论
猜你喜欢
  • 2018-01-11
  • 2021-01-31
  • 2019-05-22
  • 1970-01-01
  • 2017-07-09
  • 2018-12-12
  • 1970-01-01
  • 2020-01-07
  • 1970-01-01
相关资源
最近更新 更多