如何以编程方式触发选择下拉式onchange事件?

时间:2019-04-30 18:35:58

标签: javascript typescript

我正在页面加载时分配以下数据源“ tabNameList”。加载选择列表后,我将其分配为默认值,例如12。这将触发以下代码触发,但永远不会触发。我该如何获取代码,以便在第二次加载标签页列表并将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> 

2 个答案:

答案 0 :(得分:0)

您需要在HTML中将下拉列表中的(ngModelChange)='TabNameChanged($event)'更改为(change)="TabNameChanged($event)"

例如:

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

答案 1 :(得分:0)

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

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