Home > Back-end >  How to remove pre-selection in PrimeNg dropdown
How to remove pre-selection in PrimeNg dropdown

Time:01-01

I'm using p-dropdown from PrimeNg 15. It's a very simple dropdown.

HTML:

<form [formGroup]="myReactiveForm">
  ...
  <b>Dropdown:</b>
  <p-dropdown
    [options]="colors"
    optionLabel="name"
    formControlName="color" // <-----------Form control variable
  ></p-dropdown>
  ...
</form>

TS:

colors = [
    { name: 'black', code: 'blk' },
    ...
];

constructor() {
    this.myReactiveForm = new FormGroup({
      ...
      color: new FormControl(), // <----- kept this contructor blank
      ...
    });
}

ngOnInit() {
    this.clearForm();
}

clearForm() {
    this.myReactiveForm.controls.color.setValue(null);
}

Still I can see the first item i.e 'black' is selected in the dropdown. Please pitch in. Here is the Stackblitz.

CodePudding user response:

You need to bind [autoDisplayFirst] to the p-dropdown

   <p-dropdown
    [options]="colors"
    optionLabel="name"
    [autoDisplayFirst]="false"
    formControlName="color"
  ></p-dropdown>

The docs says about the option:

Whether to display the first item as the label if no placeholder is defined and value is null.

  • Related