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

蹲街弑〆低调 提交于 2020-04-17 22:09:41

问题


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


回答1:


Try this

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

I assume your formgroup is "form"

<form [formGroup]="form">



回答2:


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;
 } 


来源:https://stackoverflow.com/questions/60839181/set-value-of-input-based-on-the-dropdown-selected-using-formcontrolname-reacti

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!