ebhh2001
ebhh2001

Reputation: 2116

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.

Upvotes: 1

Views: 21615

Answers (3)

Prashant M Bhavsar
Prashant M Bhavsar

Reputation: 1164

To use Primeng dropdown below is simple explanation: Install primeng : npm i primeng --save

Then import it to parent module

import { DropdownModule } from 'primeng/primeng';
@NgModule({
  imports: [    
    DropdownModule
  ]
});

Add below html code to html file:

<p-dropdown 
[options]="listVariable" 
placeholder="Select" 
[(ngModel)]="selectedOption" 
(onChange)="onChangeValue()">

These are basic steps to implementation..I found very simple practical explanation here He explained it very well.

Upvotes: -1

xyntiacat
xyntiacat

Reputation: 468

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: [''])}

Upvotes: 4

mayur
mayur

Reputation: 3618

// template handling

<form id="demoForm" name="demoForm" [ngFormModel]="demoForm" (submit)="demoForm($event, demoForm)"
 method="post" action="" autocomplete="off">
<h3 class="first">Demo</h3>
<p-dropdown [options]="cities" [(ngModel)]="selectedCity"></p-dropdown>
<span *ngIf="!selectedCity"> Required </span>
<button pButton [disabled]="!selectedCity" type="submit" (click)="onclick()" label="Click"></button>
</form>

// Import the files required

import {Button} from 'primeng/primeng';
import {Dropdown} from 'primeng/primeng';

// class Handling

export class MyModel {

    cities: SelectItem[];

    selectedCity: string;

    constructor() {
        this.cities = [];
        this.cities.push({label:'Moscow', value:'1'});
        this.cities.push({label:'Istanbul', value:'2'});
        this.cities.push({label:'Berlin', value:'3'});
        this.cities.push({label:'Paris', value:'4'});
    }

   public demoForm(event: Event, demoForm: ControlGroup): void {
   event.preventDefault();

   // working area //

  }

}

Upvotes: 0

Related Questions