简体   繁体   English

Angular2单击动态生成的元素

[英]Angular2 click a dynamically generated element

I'm using a 3rd party module (a datepicker) which resolves itself as the below in the DOM (my written html only has the datepicker element) 我正在使用第三方模块(一个日期选择器),它将自己解析为DOM中的以下内容(我的书面html只有datepicker元素)

<material-datepicker>
  <div>
    <input>

I want to be able to programmatically execute a click on that input. 我希望能够以编程方式执行该输入的单击。 I've tried attaching a local var to the datepicker element but of course that item isn't listening for a click. 我已经尝试将一个局部变量附加到datepicker元素,但当然该项目不是在监听点击。 I dug in and ended up with the below which I really thought should work, but isn't... 我挖了进去,最后得到了我认为应该工作的下面的内容,但不是......

 const ref = this.datepicker.elementRef;
 const input = ref.nativeElement.querySelector('input');
 console.log('INPUT', input)
 input.click();

The output of input above is a legitmate looking input element 上面输入的输出是一个合法的输入元素

<input _ngcontent-c2="" class="datepicker__input ng-untouched ng-pristine ng-valid" readonly="true" ng-reflect-ng-style="[object Object]" ng-reflect-model="2017/06/11" placeholder="Select a date" style="color: rgb(51, 51, 51); background-color: rgb(255, 255, 255); border: 1px solid rgb(218, 218, 218);">

However the click doesn't do anything. 但是点击不会做任何事情。 I looked into the module itself and it doesn't do anything fancy on the click event so it should work. 我查看了模块本身并且它没有对click事件做任何想象,所以它应该工作。

I can't provide a jsfiddle or anything because it relies on this 3rd party module, https://github.com/koleary94/Angular-2-Datepicker 我无法提供jsfiddle或任何东西,因为它依赖于这个第三方模块, https://github.com/koleary94/Angular-2-Datepicker

I would use picker.onInputClick() method: 我会使用picker.onInputClick()方法:

template.html template.html

<material-datepicker #picker [(date)]="yourModelDate"></material-datepicker>
<button (click)="picker.onInputClick(); $event.stopPropagation()">Open manually</button>

Note $event.stopPropagation() is required here because datepicker handles document click 注意这里需要$event.stopPropagation()因为datepicker处理文档点击

Plunker Example Plunker示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM