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
CodePudding user response:
We're missing placeholder
attribute of p-dropdown
component. Please add placeholder="Please choose position"
<p-dropdown
[options]="positions"
formControlName="position"
placeholder="Please choose position" <!-- HERE
optionValue="id"
optionLabel="title"
>
CodePudding user response:
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>
CodePudding user response:
Add an object:
{
id: '',
title: 'Please select an option'
}
as the first one in the array.
You could also try mapping the same into the dynamic data.