Search code examples
angularprimengprimeng-dropdowns

How to use empty value in select box?


I have the massive of employees positions:

positions = [
    {
      id: '0',
      title: 'position0',
    },
    {
      id: '1',
      title: 'position1',
    },
    {
      id: '2',
      title: 'position2',
    },
    {
      id: '3',
      title: 'position3',
    },
];

I create reactive form. As you see, single field of this form is not initialized:

form: FormGroup = new FormGroup({
    position: new FormControl(),
});

Then i try to display this form using select box:

<div [formGroup]="form">
  <p-dropdown
    [options]="positions"
    formControlName="position"
    optionValue="id"
    optionLabel="title"
  >
  </p-dropdown>
</div>

I expect that this select box will be empty at the first load. However there is selected 'position0' value. It is a problem.

I need the displaying label like 'Please choose position'.

Here is the live example


Solution

  • I tried to quickly implement it and it worked as you wanted, your code looks ok I don't know what is missing but here is my implementation.

    In app.component.ts

    theForm: FormGroup;
    positions = [
        {
          id: '0',
          title: 'position0',
        },
        {
          id: '1',
          title: 'position1',
        },
        {
          id: '2',
          title: 'position2',
        },
        {
          id: '3',
          title: 'position3',
        },
    ];
    constructor(
     private fb: FormBuilder
    ) {}
    
    ngOnInit() {
     this.theForm = this.fb.group({
          position: new FormControl(2)
        });
    }
    

    and in app.component.html:

    <form [formGroup]="theForm">
     <p-dropdown optionLabel="title" placeholder="Please choose position" 
      [options]="positions" formControlName="position"></p-dropdown>
    </form>
    

    stackblitz