How to get the selected count, in the template, of selected items from select element in angular?

  angular, nebular

I have the following markup in my template:

<label for="restCuisine" class="label">Cuisine</label><br/>
{{ getCount(selected) }} selected
<nb-select 
    multiple 
    [(selected)]="selected"
    formControlName="restCuisine" 
    id="restCuisine">
    <nb-option value="International">International</nb-option>
    <nb-option value="Chinese">Chinese</nb-option>
    <nb-option value="Greek">Greek</nb-option>
    <nb-option value="Middle Eastern">Middle Eastern</nb-option>
    <nb-option value="Caribbean">Caribbean</nb-option>
    <nb-option value="Asian">Asian</nb-option>
    <nb-option value="Local">Local</nb-option>
    <nb-option value="Japanese">Japanese</nb-option>
    <nb-option value="Mexican">Mexican</nb-option>
    <nb-option value="Indian">Indian</nb-option>
    <nb-option value="British">British</nb-option>
    <nb-option value="European">European</nb-option>
    <nb-option value="Italian">Italian</nb-option>
    <nb-option value="French">French</nb-option>
    <nb-option value="Spanish">Spanish</nb-option>
    <nb-option value="Cajun">Cajun</nb-option>
    <nb-option value="Thai">Thai</nb-option>
    <nb-option value="Mediterranean">Mediterranean</nb-option>
</nb-select>

I’m trying to the get the selected items count like so:

selected;    

getCount(selected: any) {
    return selected.length();
}

but it doesn’t work. I tried different examples from the web but it’s not what I’m looking for. I was thinking of referencing the element using ViewChild and overriding the change event of the element then counting the items in selected but that’s too much code. I’m looking for a one or two liner.

How do I get the number of selected items of the select element? The real challenge is to do this only in the template but typescript will be fine too.

Source: Angular Questions

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.