簡體   English   中英

角度-點擊事件未在按鈕上觸發

[英]Angular - Click event not triggered on button

更新angularangular-cli ,我一直面臨着奇怪的問題。 我有兩個<div> ,當單擊按鈕時,我試圖隱藏一個並顯示另一個。

這是我的功能:

  ngOnInit() {
    this.goalView = this.el.nativeElement.getElementsByClassName('goal-view')[0];
    this.goalEdit = this.el.nativeElement.getElementsByClassName('goal-edit')[0];
  }

  triggerEdit(): void {
    this.goalView.style.display = 'none';
    this.goalEdit.style.display = 'block';
  }

  triggerView(save: boolean): void {
    this.goalEdit.style.display = 'none';
    this.goalView.style.display = 'block';
  }

和我的模板:

<div class="goal-view">
  ...
  <button class="ui right floated green button margin-vertical-10" (click)="triggerEdit()"><i class="ui edit icon"></i>Edit</button>
</div>
<div class="goal-edit">
  ...
  <button class="ui right floated green button margin-vertical-10"><i class="ui save icon" (click)="triggerView(true)"></i>Save</button>
</div>

當我單擊edit按鈕時,它起作用。 當我單擊“ save按鈕時,有時會起作用。 但是有時卻不行,我應該單擊按鈕30-40次以使其起作用。 我試圖在triggerView函數中只使用console.log("something") ,但它的作用相同。 有時有效,有時無效。

我還檢查了click事件的event.target

document.addEventListener('click', function(evt) {
    console.log(evt.target);
}, false);

看來很正常。 單擊時,它將打印正確的<button>

有什么問題的想法嗎?

通常,您不必在組件內部處理直接元素訪問。

相反,您應該切換到使用表示元素狀態的屬性。

嘗試這個

<div class="goal-view" [hidden]="hideGoalView">
...
</div>

<div class="goal-edit" [hidden]="hideGoalEdit">
...
</div>


ngOnInit() {
   this.hideGoalView = false;
   this.hideGoalEdit = true;
}

triggerEdit(): void {
   this.hideGoalView = true;
   this.hideGoalEdit = false;
}

triggerView(save: boolean): void {
   this.hideGoalView = false;
   this.hideGoalEdit = true;
}

您在image標簽而不是button標簽上具有第二個單擊偵聽器。

您將事件添加到兩個不同的元素。


方法triggerEdit按鈕標簽上的事件,因此您可以單擊整個按鈕來調用它。

方法triggerViewi元素上的事件,因此必須單擊按鈕上的小區域才能調用它。


我是否建議您認真對待@ devnull69建議。 這將為您節省將來的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM