Search code examples
javascriptangularangular4-forms

Multplication two inputs Angular


I would like get values from 2 inputs (NUM_PRECIO_UNITARIO and NUM_PORCENTAJE_IVA) and show diamically the result of multplication in other input (NUM_VALOR_IVA) actually this is my html

file.html

<div class="form-group col-sm-5">
    <mat-form-field>                    
        <input matInput type="number" formControlName="NUM_VALOR_IVA" placeholder="Valor IVA" value="{{formDetalleOC.get('NUM_PRECIO_UNITARIO').value * formDetalleOC.get('NUM_PORCENTAJE_IVA').value}}" required>                  
    </mat-form-field>
</div>  

file.ts

ngOnInit() {
    this.createControlItemOC
} 

createControlItemOC() {  
    this.formDetalleOC = this.fb.group({         
        NUM_PRECIO_UNITARIO: 0,
        NUM_PORCENTAJE_IVA: 0,   
        NUM_VALOR_IVA: 0,
    })  
}

this is the result in the front

enter image description here

but in my form the value not change

enter image description here


Solution

  • Create in function to multiply those values in your component's class

    calcResult() {
        const o = this.formDetalleOC.get('NUM_PRECIO_UNITARIO').value * this.formDetalleOC.get('NUM_PORCENTAJE_IVA').value; 
        this.formDetalleOC.patchValue({ NUM_VALOR_IVA: o });
        return o;
    }
    

    In the HTML template, call that function:

    <div class="form-group col-sm-5">
        <mat-form-field>                    
            <input matInput type="number" formControlName="NUM_VALOR_IVA" placeholder="Valor IVA" [value]="calcResult()" required>                  
        </mat-form-field>
    </div>
    

    PS: don't use ngModel for your form inputs if you are using FormBuilder (you can use it for other things on the same page).