Sravan Kumar
Sravan Kumar

Reputation: 632

set value of input based on the dropdown selected using formControlName - ReactiveForms

I have an input whose value should be based on dropdown selected. here is my code

<div class="col-sm-9">
  <nb-select type="number" fullWidth id="service" formControlName="service">
      <nb-option *ngFor="let service of Services" [value]="service">{{service.name}} </nb-option>
  </nb-select>
</div>

<input type="number value="service.price">

My .ts file

Services: Array<any>=[
    {name: 'Consultation', price: 100}, 
    {name: 'Follow Up', price: 200}, 
    {name: '24 Hrs. Creatinine', price: 300}, 
    {name: 'Complete Blood Count - CBC', price: 400}, 
    {name: 'X-Ray', price: 500}];

So when Consultation is selected, input value should be 100. Similarly when X-ray is selected, input value should be set to 500.

I want to use formControl only. ngModel is not required. Help me how can i acheive this

Upvotes: 1

Views: 1643

Answers (2)

M A Salman
M A Salman

Reputation: 3820

Try this

<input type="number" value="{{form.controls['service'].value.price}}" />

I assume your formgroup is "form"

<form [formGroup]="form">

Upvotes: 1

Michael
Michael

Reputation: 13

Have you tried using [(ngModel)] on the input field? with the ngModel binding towards the form control value equivalent

you could use callback funtion in the .ts file and the ngModel would be equal to it.

example:

getPriceEquivalent = () => {
    this.Services.forEach(x => {
      if(x.name === this.service.value){
         return x.price;
      }
    }); 
    return 0;
 } 

Upvotes: 0

Related Questions