问题
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