简体   繁体   中英

How to remove pre-selection in PrimeNg dropdown

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 ie 'black' is selected in the dropdown. Please pitch in. Here is the Stackblitz .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM