Using a PrimeNG (v12.1.0-rc.2) drop down is a matter of adding a formControlName
(see line 5) attribute on the p-dropdown component.
The setValue/getValue
methods will set and get the current selected value of the drop down. You must use the options
attribute to populate the drop down values.
Note, you will have to import FormsModule
and ReactiveformsModule
.
Source code can be found at GitHub.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div [formGroup]="formGroup"> | |
<div class="container"> | |
<div class="p-4"> | |
<h3 class="container-label">Drop Down</h3> | |
<p-dropdown optionLabel="name" styleClass="mt-4 w-72" formControlName="dropDown" [options]="cities" | |
(onChange)="onChange($event)"> | |
</p-dropdown> | |
</div> | |
</div> | |
</div> |
Then in the TypeScript code,
- Wire up the control on lines 25-27
- Set selected value on line 26
- To react to changes in the selected value see line 33
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Component, OnInit } from '@angular/core'; | |
import { FormBuilder, FormGroup } from '@angular/forms'; | |
@Component({ | |
selector: 'eyassu-ng-drop-down', | |
templateUrl: './drop-down.component.html', | |
styleUrls: ['./drop-down.component.scss'] | |
}) | |
export class DropDownExComponent implements OnInit { | |
cities: City[] = [ | |
{ name: 'New York', code: 'NY' }, | |
{ name: 'Rome', code: 'RM' }, | |
{ name: 'London', code: 'LDN' }, | |
{ name: 'Istanbul', code: 'IST' }, | |
{ name: 'Paris', code: 'PRS' } | |
]; | |
formGroup!: FormGroup; | |
constructor(private fb: FormBuilder) { } | |
ngOnInit(): void { | |
this.formGroup = this.fb.group({ | |
dropDown: this.cities[2] // preselect a value | |
}); | |
} | |
// eslint-disable-next-line @typescript-eslint/no-explicit-any | |
onChange(event: Event) { | |
// Obtain selected value | |
const selectedCity = this.formGroup.get('dropDown')?.value; | |
console.log(JSON.stringify(selectedCity)); | |
} | |
} | |
interface City { | |
name: string, | |
code: string | |
} |