2017-06-17 168 views
1

我使用的是第三方模塊(日期選擇器),它解決了自身作爲下面的DOM(我寫HTML只具有日期選擇器元素)Angular2點擊動態生成的元素

<material-datepicker> 
    <div> 
    <input> 

我想能夠以編程方式執行對該輸入的點擊。我已經嘗試將一個本地var附加到datepicker元素,但當然,該項目不在監聽點擊。我挖,結束了與低於此我真的認爲應該工作,但不...

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

輸入輸出上面是legitmate尋找輸入元素

<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);"> 

然而,點擊不做任何事情。我研究了模塊本身,並且它沒有對click事件做任何事情,所以它應該可以工作。

,因爲它依賴這個第三方模塊上我不能提供的jsfiddle或任何東西,https://github.com/koleary94/Angular-2-Datepicker

+0

你期待什麼發生?如果您將單擊事件綁定到輸入,我們可以看到那段代碼嗎?或者你只是想着重於輸入? –

+0

當'input.click()'執行時,你期望發生什麼?你有一個正在監聽點擊事件的處理程序嗎? –

+0

爲什麼不是[** Material2#datepicker **](https://material.angular.io/components/component/datepicker)? :) – developer033

回答

0

我會用picker.onInputClick()方法:

template.html

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

注這裏需要$event.stopPropagation(),因爲datepicker處理文檔點擊

Plunker Example

+0

非常感謝yurzui,這是我失蹤的topPropagation! –