Angular - Click event not triggered on button

After I updated angular and angular-cli, I keep facing strange problems. I have two <div>s and I am trying to just hide one and show the other when a button clicked.

Here is my functions:

  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';
  }

And my template:

<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>

When I click edit button, it works. When I click the save button, it works, sometimes. But sometimes it does not, I should click the button 30-40 times to make it work. I tried to just console.log("something") in the triggerView function, but it does the same. Sometimes works and sometimes does not.

I also checked the event.target of the click events:

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

It seems normal. It prints the correct <button> when I clicked.

Any idea on what should be the problem?

Upvotes: 0

Views: 3740

Answers (3)

Jaroslaw K.
Jaroslaw K.

Reputation: 5374

You add events to two different elements.


Method triggerEdit is event on button tag, so you can click on whole button to called it.

Method triggerView is event on i element, so you must click small area on button to call it.


whether I suggest you take seriously @devnull69 advice. This will save you problems in the future.

Upvotes: 0

cy3er
cy3er

Reputation: 1699

You have the second click listener on the image tag instead of the button tag.

Upvotes: 2

devnull69
devnull69

Reputation: 16544

Generally, you should not have to deal with direct element access inside your Component.

Rather you should switch over to using properties representing the state of elements.

Try this

<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;
}

Upvotes: 5

Related Questions