【问题标题】:How to Programmatically Trigger 'Click' Event in Angular 6?如何以编程方式触发 Angular 6 中的“点击”事件?
【发布时间】:2019-01-22 08:04:58
【问题描述】:

本质上,我想使用 TypeScript 触发页面中的输入按钮

【问题讨论】:

标签: events onclick angular6


【解决方案1】:

JS代码:

document.getElementById('mat-checkbox-1-input').click();

编码愉快!!!

【讨论】:

    【解决方案2】:

    //这和在原生 JS 中做没有什么不同

    let elem = document.getElementById('submitBtn');
    
    let evt = new MouseEvent('click', {
            bubbles: true,
            cancelable: true,
            view: window
        });
    
    elem.dispatchEvent(evt);
    

    【讨论】:

    • 我收到错误 -ERROR TypeError: Cannot read property 'dispatchEvent' of null
    【解决方案3】:

    在 .ts 中按如下方式使用@ViewChild

     @ViewChild('fileInput') fileInput: ElementRef;
    
     let inputElement: HTMLElement = this.fileInput.nativeElement as HTMLElement;
     inputElement.click();
    

    在您的 .html 中,

     <input #fileInput type="file" ng2FileSelect (onFileSelected)="fileUpload($event)"/>
    

    【讨论】:

      猜你喜欢
      • 2012-03-18
      • 1970-01-01
      • 2016-06-12
      • 2019-01-15
      • 2021-06-04
      • 1970-01-01
      • 2021-08-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多