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.
Using NgModel Directive Angular has another way to get the selected value in the dropdown using the power of ngModel and two-way data binding. The ngModel is part of the forms module. We need to import it into the NgModule list in the app. module , which will be available in our app.
The value of the selected element can be found by using the value property on the selected element that defines the list. This property returns a string representing the value attribute of the <option> element in the list. If no option is selected then nothing will be returned.
Go to 'ng-select component and search something you get some option regarding it. ' Click OR select the option. And after the selection the value Cursor focus out from the component.
The ng-selected directive sets the selected attribute of an <option> element in a <select> list. The option will be selected if the expression inside the ng-selected attribute returns true. The ng-selected directive is necessary to be able to shift the value between true and false .
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With