Search code examples
javascriptarraysjsonangularbootstrap-typeahead

angular 4 typeahead display only property that has a match in array of objects?


I have an array of json and two typeahead channels and shows. The value of show depend on the value of channel selected.

allChannelShow = [    
{"channel":"tv","showname":["America","Friends","Night"]}, 
{"channel":"radio","showname":["360","pop","News","Special","Prime Time"]}, 
{"channel":"stream","showname":["All In","Reports","Deadline","series","Morning","Live","drama","comedy"]}   
]   

my .html file

<div class="container">       
   <label for="channel">Channel 
     <input formControlName="channel" [typeahead]="allChannelShow" typeaheadOptionField="channel" [typeaheadOptionsLimit]="10" [typeaheadMinLength]="0" 
      placeholder="Enter a channel name" required>                                  
   </label>              
</div>
<div class="container">     
  <label>Show                               
    <div *ngIf="channel"> 
      <input formControlName="show" [typeahead]="allChannelShow" typeaheadOptionField="showname" [typeaheadOptionsLimit]="10" [typeaheadMinLength]="0" placeholder="Enter a show name" required>
</div>   </label> </div> 

So if I select :
radio, the second typeahead shows will have a select list with these items:
["360","pop","News","Special","Prime Time"]
And I will be able to select a specific a show like News or 360 or pop not the whole list if I select :
tv, the second typeahead shows will have a select list with these items: [ {"channel":"tv","showname":["America","Friends","Night]
I will be able to select a specific show like friends not the whole list

How can I make it happen?

Update Here is the code for what I have now.


Solution

  • Create a method that returns the show names for a given channel name:

    getShowNames(channel: string): string[] {
      const channelEntry = this.allChannelShow.find(c => c.channel === channel);
      return channelEntry ? channelEntry.showname : [];
    }
    

    Assign a template variable to your input so you can retrieve its value

    <input #channelInput formControlName="channel" [typeahead]="allChannelShow" typeaheadOptionField="channel" [typeaheadOptionsLimit]="10" [typeaheadMinLength]="0">
           ^^^^^^^^^^^^^
    

    Set the autocomplete values dynamically with the method and the currently selected channel.

    <input formControlName="show" [typeahead]="getShowNames(channelInput.value)" typeaheadOptionField="showname" [typeaheadOptionsLimit]="10" [typeaheadMinLength]="0" placeholder="Enter a show name" required>
                                              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    

    Try it out in this stackblitz.