简体   繁体   中英

Angular formControlName - reactive form - Setting values to primeNg p-dropdown

I have a component.html that has dropdown of type list of Users object.

The p-dropdown list in HTML looks like follows:

<div class="col-sm-4">
        <p-dropdown [options]="usersList" formControlName="assignedTo" optionLabel="name"  placeholder=" Select "></p-dropdown>
</div>

And the inspect element for the same is as below:

<p-dropdown class="ng-tns-c54-11 ng-untouched ng-pristine ng-valid" ng-reflect-options="[object Object],[object Object" formControlName="assignedTo" ng-reflect-name="assignedTo" placeholder=" Select " ng-reflect-placeholder=" Select " optionLabel="name" ng-reflect-option-label="name">
<div class="ng-tns-c54-11 ui-dropdown ui-widget ui-state-default ui-corner-all" ng-reflect-ng-class="[object Object]">
<div class="ui-helper-hidden-accessible ng-tns-c54-11">
<input class="ng-tns-c54-11" role="listbox" aria-haspopup="listbox" aria-label=" " type="text" readonly=""></div>
<div class="ui-dropdown-label-container ng-tns-c54-11" ng-reflect-text="" ng-reflect-tooltip-position="right" ng-reflect-position-style="absolute"><!--bindings={
  "ng-reflect-ng-if": "false"
}--><label class="ng-tns-c54-11 ui-dropdown-label ui-inputtext ui-corner-all ui-placeholder ng-star-inserted" ng-reflect-ng-class="[object Object]"> Select </label><!--bindings={
  "ng-reflect-ng-if": "true"
}--><!--bindings={}--><!--bindings={}--></div><div class="ui-dropdown-trigger ui-state-default ui-corner-right ng-tns-c54-11" role="button" aria-haspopup="listbox"><span class="ui-dropdown-trigger-icon ui-clickable ng-tns-c54-11 pi pi-chevron-down" ng-reflect-ng-class="pi pi-chevron-down"></span></div><!--bindings={}--></div></p-dropdown>

Users model has the field 'name' which is nothing but firstName +','+lastName. they are displayed correctly in the dropdown. How do i set the dropdown to a particular name dynamcially?

I tried to assign it to formControlName 'assignedTo' like below but wouldnt work,

this.createDiscrepancyForm.setValue({
assignedTo: event.data.assignedTo.name,
})

But the dropdown doesnt change. Can someone please help.I tried other dropdowns which has lookup values and it works perfectly fine. But this has issue.

In your case you need to set value of assignedTo FormControl with the user model because this is currently held as dropdown value, not just name proprety. If you want dropdown value to be just name property then you need to map your current usersList collection to PrimeNG's SelectItem collection which have label and value properties and pass this as options into the p-dropdown in template.

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