Whenever I click on my #dropDown button, it functions as intended and opens the dropdown menu; however, the click also hits the underneath which is also clickable. I don't want the button click event to also hit the div underneath, as that is not the intended function.
<ul #postCard *ngFor="let post of posts; let i = index" [class.selected]="getSelected() == i || currPost == post" (click)="setSelected(i)" (click)="setPost(post)" id="jobcard" >
<li >
<div >
<h2 >{{post.title}}</h2>
<div [style.display]="'block'">
<h2 id="dateofjob" >{{post.date_of_job}}</h2>
</div>
</div>
<div >
<div>
<h2 >Description:</h2>
<p>{{post.care_description}}</p>
</div>
<p id="timeofjob" >Start: {{post.start_time}} | End: {{post.end_time}}</p>
</div>
<div >
<div >
<button #dropDown (click)="toggleDropdown()" >
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
<path fill-rule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" clip-rule="evenodd" />
</svg>
</button>
<div *ngIf="shown" >
<h2 >Your Application: </h2><a > {{post.applications[0].message}} </a>
</div>
</div>
</div>
</li>
</ul>
CodePudding user response:
try using stopPropagation in the click function.
check out this link for more details: https://www.freecodecamp.org/news/a-simplified-explanation-of-event-propagation-in-javascript-f9de7961a06e/
CodePudding user response:
It's happening because the event are bubbling, both the clicks on the button and the div get registered. We can tell our function to stop further propagation of the current event by using event.stopPropagation()
In your, capture the $event in your function as a parameter HTML
<button #dropDown (click)="toggleDropdown($event)" >
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
<path fill-rule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" clip-rule="evenodd" />
</svg>
</button>
and then in your .ts component, use that event to stop further bubbling of events, so that the div click won't be called:
toggleDropdown($event: Event):void {
$event.stopPropagation();
}
