Last active
July 25, 2021 07:22
-
-
Save ierhalim/944ba351e84d27e47acf4e79f3c4e099 to your computer and use it in GitHub Desktop.
PrimeNG Employee dropdown.
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
<p-dropdown appEmployeeDropdown></p-dropdown> |
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'; | |
@Component({ | |
selector: 'app-root', | |
templateUrl: './app.component.html', | |
styleUrls: ['./app.component.css'], | |
}) | |
export class AppComponent implements OnInit { | |
ngOnInit() { | |
// No code required for employee dropdown. | |
} | |
} |
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 { HttpClient } from '@angular/common/http'; | |
import { Directive, OnInit, Self, OnDestroy } from '@angular/core'; | |
import { Dropdown } from 'primeng/dropdown'; | |
import { map } from 'rxjs/operators'; | |
import { Subscription } from 'rxjs'; | |
@Directive({ | |
selector: '[appEmployeeDropdown]', | |
}) | |
export class EmployeeDropdownDirective implements OnInit, OnDestroy { | |
getEmployeeSubscription: Subscription; | |
constructor( | |
// Injecting the Dropdown component instance. | |
@Self() private readonly primeDropdown: Dropdown, | |
private readonly httpClient: HttpClient | |
) {} | |
ngOnInit() { | |
// You can set all inputs and subscribe to all outputs, by injected instance. | |
this.primeDropdown.filter = this.primeDropdown.showClear = true; | |
this.primeDropdown.placeholder = "Choose an employee" | |
this.getEmployeeSubscription = this.httpClient | |
.get<Array<any>>( | |
'https://my.api.mockaroo.com/employees.json?key=35003520' | |
) | |
.pipe( | |
map((rawData) => { | |
return rawData.map((employe) => ({ | |
value: employe.id, | |
label: `${employe.firstName} ${employe.lastName}`, | |
})); | |
}) | |
) | |
.subscribe((employees) => { | |
this.primeDropdown.options = employees; | |
},(error) => { | |
// TODO: Handle errors | |
}); | |
} | |
ngOnDestroy(){ | |
// You should unsubscribe from subscribed outputs to prevent memory leaks. | |
if(!!this.getEmployeeSubscription){ | |
this.getEmployeeSubscription.unsubscribe(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment