Retrive selected value of ng-select - Angular8
First in .ts file i created object:
cities4 = [];
selectedCityIds: string[];
Second, install npm i @ng-select/ng-select
:
Next add:
<ng-select [items]="cities4"
[virtualScroll]="true"
bindLabel="name"
bindValue="id"
placeholder="Select city"
[(ngModel)]="selectedCityId">
</ng-select>
You can use the change
event to capture the selected value.
<!-- Template -->
<ng-select (change)="changeFn" class="w-25 p-3" placeholder="{{'author' | translate}}" [clearable]="false" [searchable]="false">
<ng-option>{{'author' | translate}}</ng-option>
<ng-option>{{'title' | translate}}</ng-option>
<ng-option>{{'date' | translate}}</ng-option>
</ng-select>
<!-- Component ts file -->
changeFn(val) {
console.log(val);
}
Add the [(ngModel)]
attribute to the attributes of the ng-select
, and pass its value to the triggering.
<ng-select (change)="changeFn(selection)" [(ngModel)]="selection" class="w-25 p-3" placeholder="{{'author' | translate}}" [clearable]="false" [searchable]="false">
<ng-option>{{'author' | translate}}</ng-option>
<ng-option>{{'title' | translate}}</ng-option>
<ng-option>{{'date' | translate}}</ng-option>
</ng-select>
Then in the ts file:
export class myComponent {
public val: string;
changeFn(val) {
console.log("Dropdown selection:", val);
}
}