Reputation: 268
I am a novice with Angular 8.
I created the following dropdown menu, in a component, that works very well for me:
<ng-select 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>
Now I would like to know how I can retrive the selected element in the ts
file of the same component.
Thanks in advance.
Upvotes: 18
Views: 66961
Reputation: 878
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>
Upvotes: 3
Reputation: 131
you can add >> [ngModelOptions]="{standalone: true}" to get value
<div class="col-sm-10 text-left">
<ng-select
[items]="countries.countries"
bindLabel="country"
bindValue="country_code"
[ngModelOptions]="{standalone: true}"
[(ngModel)]="selectedCountry" (change)="getCountry()">
</ng-select>
</div>
Upvotes: 5
Reputation: 268
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);
}
}
Upvotes: 7
Reputation: 2984
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);
}
Upvotes: 10