Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular PrimeNG dropdown component in reactive forms - initial value

using primeNg dropdown component, I'm trying to initialized the dropdown with initial value with no success, I'm using reactive approach.

I checked the primeNg documentation and demos - almost all the examples there are using template driven, I would like to have the same with model driven.

I'm able to render the dropdown with the values in the list but the selected item is not the one I declared in the form, instead it's the first item in the list.

my code: template

    <div [formGroup]="formGroup">
      <p-dropdown [options]="results"
                 formControlName="second"
                (onChange)="onChangeHandler($event)"
                optionLabel="label">
       </p-dropdown>
    </div>

component

  this.second = new FormControl('second');
  this.formGroup= this.builder.group({
            second: this.second
        });


    this.results = [];
    this.results.push({ label: 'First Data', value: "first" });
    this.results.push({ label: 'Second Test Data', value: "second" });
    this.results.push({ label: 'Third Data', value: "third" });

Please advise.

If anyone can share a working example of primeNG dropdown component in model driven it would be great. The values should have key, value attributes like in my example.

like image 531
john Smith Avatar asked Oct 23 '25 14:10

john Smith


1 Answers

Since the FormControl named second is a part of the your FormGroup, the instantiation should be inside the FormGroup itself. Consider the following example,

this.formGroup= this.builder.group({
    second: new FormControl('second')
});
like image 142
Fiyaz Hasan Avatar answered Oct 26 '25 14:10

Fiyaz Hasan