Search code examples
angulardropdownprimeng

How to use PrimeNG Dropdown in Angular2 Model-driven form?


Need help with PrimeNG dropdown in an Angular2 model-driven form. The PrimeNG documentation I have found only use template-driven forms.

A sample code for the following would help greatly:

  1. an Angular model-driven form
  2. the form contains one PrimeNG dropdown and a submit button.
  3. the dropdown contains 4 cities (Moscow, Istanbul, Berlin, Paris).
  4. the user is required to change the selected city (to enable the Submit button).
  5. the dropdown can be programatically "initialized" to show one of the cities in the options list (e.g. Berlin) when the form first opens.

Thanks.


Solution

  • To use the model driven form in Angular2 or Angular4 you'll need to change the dropdown to

    <p-dropdown [options]="cities" formControlName="selectedCity"></p-dropdown> 
    

    and instantiate a formGroup on the backend that has the control selectedCity in it like so ...

    this.angularObjectForm = this.formBuilder.group({selectedCity: [''])}