Angular PrimeNG dropdown component in reactive forms - initial value

守給你的承諾、 提交于 2019-12-23 01:57:12

问题


using primeNg dropdown component, I'm trying to initialized the dropdown with initial value with no success, I'm using reactive approach.

I checked the primeNg documentation and demos - almost all the examples there are using template driven, I would like to have the same with model driven.

I'm able to render the dropdown with the values in the list but the selected item is not the one I declared in the form, instead it's the first item in the list.

my code: template

    <div [formGroup]="formGroup">
      <p-dropdown [options]="results"
                 formControlName="second"
                (onChange)="onChangeHandler($event)"
                optionLabel="label">
       </p-dropdown>
    </div>

component

  this.second = new FormControl('second');
  this.formGroup= this.builder.group({
            second: this.second
        });


    this.results = [];
    this.results.push({ label: 'First Data', value: "first" });
    this.results.push({ label: 'Second Test Data', value: "second" });
    this.results.push({ label: 'Third Data', value: "third" });

Please advise.

If anyone can share a working example of primeNG dropdown component in model driven it would be great. The values should have key, value attributes like in my example.


回答1:


Since the FormControl named second is a part of the your FormGroup, the instantiation should be inside the FormGroup itself. Consider the following example,

this.formGroup= this.builder.group({
    second: new FormControl('second')
});


来源:https://stackoverflow.com/questions/47402327/angular-primeng-dropdown-component-in-reactive-forms-initial-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!