I have a select field in my Angular Reactive Form and i want to pull the value of text inside the <option>
tag which the user selects and then dynamically fill its value in the input (like on change event)
COMPONENT.HTML
<div class="form-group">
<label>Select Plant</label>
<select class="form-control" formControlName="plantId" name="plantId" id="plantId">
<option [ngValue]="1">ABC</option>
<option [ngValue]="2">XYZ</option>
</select>
<app-control-messages [control]="storlocForm.get('plantId')"></app-control-messages>
</div>
<div class="form-group">
<label>Plant Name *</label>
<input id="plantName" class="form-control" type="text" formControlName="plantName" name="plantName" value="" />
</div>
Suppose if the user selects XYZ from the dropdown i want the value "XYZ" to be filled in the following input (plantName) not the value "2".
COMPONENT.TS
this.storlocForm = this.formBuilder.group({
plantId: ['', Validators.required],
plantName: ['']
});
}
just add the change event to the select element and update the formcontrol like below.
<select class="form-control" formControlName="plantId" name="plantId" id="plantId" (change)="update($event)">
<option [ngValue]="1">ABC</option>
<option [ngValue]="2">XYZ</option>
</select>
update(event): void {
let plantName = event.target.options[event.target.options.selectedIndex].text;
this.form.controls.plantName.setValue(plantName);
}