how do i bind formcontrol to an object with the object id?

Try below approach

  • Create a holder property otherSelected
  • Watch the change in the dropdown using (ngModelChange)
  • Update value of the form using setValue

see below code and demo on Stackblitz

<div [formGroup]="myForm">
    <div class="id-field"><input type="text" formControlName="id"></div>
    <div class="name-field"><input type="text" formControlName="name"></div>
    <div class="otherId-field">
        <p-dropdown [(ngModel)]='otherSelected' (ngModelChange)='myForm.get("otherId").setValue(otherSelected.id)' dataKey='id' [options]="options"
                optionLabel="name" [ngModelOptions]="{standalone: true}">
        </p-dropdown>
    </div>

    </div>
    <pre>{{ myForm.value | json }}</pre> {{ otherSelected | json }}
  name = "Angular " + VERSION.major;
  otherSelected: { id: number | null } = { id: null };
  myForm = this.fb.group({
    id: [null],
    name: [""],
    otherId: [null]
  });

  options = [
    {
      id: 1,
      name: "option A"
    },
    {
      id: 2,
      name: "option B"
    },
    {
      id: 3,
      name: "option C"
    }
  ];

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top