Home > Mobile >  Angular - How to populate the empty input field when the dropdrown is selected
Angular - How to populate the empty input field when the dropdrown is selected

Time:07-20

I'm trying to create the DropdownBox that will populate input fields once I selected the value,

{ name:'Arnold', item:'Laptop' } 

The dropdown contains the Name once I selected "Arnold" it will populate the other empty textbox with "Laptop". How do achieve that?

So far this is what I code: https://stackblitz.com/edit/mat-dialog-example-qzg1ea

CodePudding user response:

Besides the issue that I mentioned in the comment.

Actually, you are almost near to the answer.

<mat-select
    (selectionChange)="selectedType($event)"
    formControlName="name"
    style="width:200px"
  >
  <mat-option *ngFor="let item of items" [value]="item.name">
    {{ item.name }}
  </mat-option>
</mat-select>

You need the selectionChange event to trigger when the dropdown is selected/changed.

selectionChange: EventEmitter<C>

Event emitted when the selected value has been changed by the user.

In the selectedType method, find the selected item from the items array. If the item is found, use .patchValue() to patch the value to item control.

items = ELEMENT_DATA;

selectedType(trigger: MatSelectChange) {
  ...

  const selectedItem = this.item.find((x) => x.name == trigger.value);
  if (selectedItem) this.fg.controls.item.patchValue(selectedItem.item);
}

Sample StackBlitz Demo

  • Related