angular 4 typeahead仅显示在对象数组中具有匹配项的属性?

时间:2018-07-23 16:15:52

标签: javascript arrays json angular bootstrap-typeahead

我有一个json数组和两个预输入频道并显示。 show的值取决于所选频道的值。

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"]}   
]   

我的.html文件

<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> 

所以,如果我选择:
radio,第二场预演节目将有一个选择列表,其中包含以下项目:
 ["360","pop","News","Special","Prime Time"]
我将能够选择特定的节目,例如News360pop,而不是整个列表 如果我选择:
tv,第二个要输入的shows将具有包含以下各项的选择列表:[ {"channel":"tv","showname":["America","Friends","Night]
 我将可以选择一个特定的节目,例如friends而不是整个列表

我该如何实现?

更新 这是我现在拥有的code

1 个答案:

答案 0 :(得分:1)

创建一个返回给定频道名称的节目名称的方法:

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

将模板变量分配给您的输入,以便您可以检索其值

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

使用方法和当前选择的通道动态设置自动完成值。

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

在此stackblitz中尝试一下。