0

I am trying to auto populate an input field based on the selected value of a dropdown. The following is the code and it is not working. Please suggest.

<form [formGroup]="employeeForm" (ngSubmit)="OnSubmit()"> <mat-form-field appearance="outline"> <mat-label>Employee ID</mat-label> <input type="text" placeholder="Employee ID" required formControlName="employeeidControl" matInput [matAutocomplete]="auto1"> <mat-autocomplete #auto1="matAutocomplete"> <mat-option *ngFor="let employee of employees" [value]="employee.id"> {{ employee.id }} </mat-option> </mat-autocomplete> <mat-error> Employee ID is required </mat-error> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Employee Name</mat-label> <input type="text" matInput placeholder="Employee Name" value="{{employeeidControl.name}}" required formControlName="employeenameControl"> <mat-error> Employee Name is required </mat-error> </mat-form-field> </form> 
6
  • You should be able to read it of your form.. but you haven’t shown your formGroup.. Commented Jan 15, 2021 at 17:56
  • I updated the form Commented Jan 15, 2021 at 18:04
  • I think employeeForm.get(‘ employeeidControl’).value should work? Commented Jan 15, 2021 at 18:06
  • I understood. Its writing only IDs...but I want to write the relative names of the IDs Commented Jan 15, 2021 at 18:10
  • Your putting the id in the form. So you can out the whole object in there instead and read the name value Commented Jan 15, 2021 at 18:12

1 Answer 1

1

If I understood correctly, you want to fill in the Name field based on the selected ID? Maybe in your mat-option put click event and pass the name to the ts. So:

<mat-option *ngFor="let employee of employees" [value]="employee.id" (click)="test(employee.name)"> {{ employee.id }} </mat-option> 

and in ts:

 test(employeeName){ this.employeeForm.get('employeenameControl').patchValue(employeeName) } 
Sign up to request clarification or add additional context in comments.

3 Comments

But I want to populate the employee name value in input field
you tried the code above? it populate the field 'employeenameControl' with the employee name based no the selected ID. So if you select "id 1" the field it fills up with "nameemployee 1" (for example)
Ok. Got it. Will let you know.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.