简体   繁体   中英

p-dropdown doesn't show value from form

I'm getting a problem when I use the p-dropdown component binding a form. I have a Form Group with Form Controls that have our own values pre-loaded and the value of one of this controls should be showed at p-dropdown component. But it isn't visible when the page load.

I use the Dropdown look like:

<p-dropdown [options]="vehicleTypes" placeholder="Vehicle Type" optionLabel="label" formControlName="vehicleType">

And my component have a Form Group that have a Form Control named vehicleType and with the value.

{label: "TYPE 1", value: "1"}

Why are you having label in formcontrol? Just keep value in formControl like this:

app.component.ts

appForm: FormGroup;

vehicles = [
 {value: 1, label: 'v1'},
 {value: 2, label: 'v2'},
 {value: 3, label: 'v3'},
 {value: 4, label: 'v4'},
 {value: 5, label: 'v5'},
 {value: 6, label: 'v6'},
]

constructor(
 private fb: FormBuilder
) {}

ngOnInit() {
this.appForm = this.fb.group({
  vehicleType: new FormControl(2)
});

app.component.html

<form [formGroup]="appForm">
 <p-dropdown [optionLabel]="label" placeholder="Vehicle Type" 
  [options]="vehicles" formControlName="vehicleType"></p-dropdown>
</form>

The values have to be set to your vehicleTypes like:

vehicleTypes = [
    {label: "TYPE 1", value: "1"}
]

and vehicleType is a FormControl like Bravin said.

Generally, we could use first element as a placeholder.

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