Issue
A lot is written about this problem, but all answers suggests one or more of the following:
stopPropagation
preventDefault
return false
.
But non is working in my case. Here is stackblitz. When button is clicked, desired behaviour is that console shows:
click - button
stop
but it also shows
Click from app component - but it shouldn't happened
This click shouldn't happen (in app.component
):
<my-button [disabled]="true" (click)="onClick()"></my-button>`
public onClick()
{
console.log("Click from app component - but it shouldn't happened");
}
One solution is provided here. But, is creating another span element. Is this really the only option?
Also
native add and remove EventListeners
doesn't looks as elegant solution.
Solution
Remove the HostListener
and add a click listener for the button
in my-button
component.
Plus, you don't need the additional this.click.emit()
since it's automatically going to propagate if stopPropogation
is not called.
Template
<button (click)='onClick($event)'>{{text}}</button>
When the button is clicked, the onClick
in my-button
is called, based on some logic you can either choose to emit or discard the click
.
@Component({
selector: "my-button",
template: `<button (click)='onClick($event)'>{{text}}</button>`
})
export class MyButton
{
@Input() disabled = false;
@Input() text = "Click me";
@Output() click = new EventEmitter();
public onClick(event: Event)
{
console.log("click - button");
if (!this.disabled)
console.log("click emit");
else
{
console.log("stop");
event.stopPropagation();
}
}
}
Stackblitz
Answered By - cyberpirate92
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.