首页 > 解决方案 > 如何以编程方式触发 select dropdown onchange 事件?

问题描述

我在页面加载时分配了以下数据源“tabNameList”。在它加载选择列表之后,我将它分配给它的默认值,比如说 12。这应该会触发下面的代码,但它永远不会触发。如何让代码在加载 tablist 并且 selectedTabId 设置为 12 时触发第二个?

设置代码

 LoadTabNames(){
    this._userProfileService.loadTabNames(this.screenId).subscribe(data => { 
      this.DisableTab= false;             
      this.tabNameList = data[0];
      this.selectedTabId = data[0]["ScreenId"]  <----- TabNameChanged event should fire right here since the ngModel has changed        
      this.cdr.detectChanges();      
    })
  }

TabNameChanged(event){
      this.selectedColumns = [];
      this.availableColumns = [];     

      // When the tab select changes load the new headers into the First ListBox
      const detailList = filterBy(this.UserProfileTabData, {
        logic: 'and',
        filters: [
          { field: 'ScreenId', operator: 'eq', value: this.screenId, ignoreCase: true },
          { field: 'TabId', operator: 'eq', value: event, ignoreCase: true }
        ]
      });
       detailList.forEach(element => {
        this.selectedColumns.push(element["ColumnName"]);        
      });

    }

我的html

<div class="col">             
                  <label for="dropdown2">Tab Name</label>
                  <select #tab class="custom-select custom-select-lg mb-3" id="dropdown2" [disabled]='DisableTab' (ngModelChange)='TabNameChanged($event)' [(ngModel)]="selectedTabId">                  
                        <option *ngFor="let tab of tabNameList let i=index" [(ngValue)]="tab.TabId" >{{tab.TabName}}</option>                
                      </select>                 
       </div> 

标签: javascripttypescript

解决方案


您可以使用以下代码随时触发元素的事件:

let element = document.getElementById(id);
element.dispatchEvent(new Event("change"));

推荐阅读