angularonclickprimengp-dropdown

How to auto-select the p-drodown Option from Ts functionality? - Angular PrimeNG


<p-dropdown
                  class="form-right-column mt-6"
                  [options]="states"
                  filterBy="name"
                  [formControl]="$any(formGroup).get('state')"
                  optionLabel="name"
                  [editable]="true"
                  (onFilter)="customFilter($event)"
                  placeholder="Select State"
                ></p-dropdown>

I have this and I am triggering another click function which is

<p-button
                    (click)="confirm($event)"
                    icon="pi pi-check"
                    label="Confirm"
                  ></p-button>

I want to write autos elect to Gujarat state if this button clicked.


Solution

  • You can use patchValue to do this!

    confirm(event: any) {
        const stateCtrl = this.formGroup.get('state');
        if(stateCtrl) {
            // if you are using an id then patch value the gujarat id instead!
            stateCtrl.patchValue('Gujarat', { emitEvent: false }); // this can be the key of the dropdown
            // if above does not work you can try
            // const gujarat = this.options.find((x: any) => x.name === 'Gujarat') ||  null;
            // if(gujarat) {
            //     stateCtrl.patchValue(gujarat, { emitEvent: false });
            // }
        }
    }