简体   繁体   中英

change input value by component

guys I have an input that when changing the value it executes a function in the component

    <input class="form-control" (change)="updateQuantidade($event.target.value, item)" type="number" name="quantity" min="1" max="{{item.estoque.estAtual}}" value="{{item.quantidade}}">



updateQuantidade(value: string, item: IItem) {
this.quantidade = Number(value);
if (Number(value) > item.estoque.estAtual) {
  this.quantidade = this.item.estoque.estAtual;
  item.quantidade = this.quantidade
  this.modalS.createModal(MdAlertComponent, { title: 'Estoque insuficiente', message: `Só há ${item.estoque.estAtual} unidade(s) deste item em estoque` });
}

}

if item.quantidade is greater than item.estoque.estAtual

it changes the value of this.quantidade for the same value of this.item.estoque.estAtual

in the component it changes the value, but in the input it remains the old value, can someone help me with this?

在此处输入图像描述

<div class="col-sm-5">
<dt *ngIf="this.quantidade > item.estoque.estAtual" 
style="padding-right: 10px;">Em estoque: 
{{item.estoque.estAtual}} </dt>
<h5>{{this.quantidade}}</h5>this.quantidade
<h5>{{item.estoque.estAtual}}</h5>item.estoque.estAtual

<dl class="dlist-inline">
<dt style="padding-right: 10px;">Quantidade: </dt>
<dd>
    <input class="form-control" [(ngModel)]="this.quantidade" 
(ngModelChange)="updateQuantidade(item)" type="number" 
name="quantity" min="1" max="{{item.estoque.estAtual}}" >

<!--<input class="form-control" 
(change)="updateQuantidade($event.target.value, item)" 
type="number" name="quantity" min="1" max=" 
{{item.estoque.estAtual}}" value="{{item.quantidade}}">
--></dd>
  </dl>
<div>
  </div>
</div>

The new html code

<input
class="form-control"
[(ngModel)]="quantidade"
                          
(ngModelChange)="updateQuantidade(item)"
type="number"
name="quantity"
min="1"
/>

You need to use [(ngModel)]="this.quantidade" instead of using the $event.target.value, and use (ngModelChange) to call a function on change. Note: you don't need to use value="{{item.quantidade}}" anymore since [(ngModel)] will automatically bind the input to this.quantidade .

In your .html file:

<input 
   class="form-control" 
   [(ngModel)]="quantidade"
   (ngModelChange)="updateQuantidade(item)" 
   type="number" 
   name="quantity" 
   min="1" 
/>

In your component.ts file:

updateQuantidade( item: IItem) {
  if (this.quantidade > item.estoque.estAtual) {
    this.quantidade = this.item.estoque.estAtual;
    item.quantidade = this.quantidade
    this.modalS.createModal(MdAlertComponent, { title: 'Estoque insuficiente', 
    message: `Só há ${item.estoque.estAtual} unidade(s) deste item em estoque` 
   });
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM