Angular 5中如何阻止子元素的点击事件?
Hey there! I totally get why this is frustrating—you set up the click event only on the parent element, but clicking those newly added li items (or any child inside the parent) is still triggering the add logic. That's down to event bubbling in the browser: when you click a child element, the event travels up the DOM tree and fires the parent's click handler too.
Let's go through a couple of straightforward fixes tailored to your Angular setup:
1. Use Angular's self Event Modifier (Easiest Fix)
Angular has built-in event modifiers that make this a one-line change. Just add .self to your parent's click event binding. This ensures the event only fires when you click the parent element itself, not any of its children.
Example template change:
<!-- Before --> <div (click)="addNewItem()"> <ul> <li *ngFor="let item of items">{{ item }}</li> </ul> </div> <!-- After --> <div (click.self)="addNewItem()"> <ul> <li *ngFor="let item of items">{{ item }}</li> </ul> </div>
That's it! No extra code needed in your component class.
2. Check Event Target in Your Handler (More Flexible)
If you need more control (like conditionally allowing some children to trigger the event), you can modify your component's click handler to check if the clicked element is actually the parent.
First, update your template to pass the event object:
<div (click)="addNewItem($event)"> <ul> <li *ngFor="let item of items">{{ item }}</li> </ul> </div>
Then adjust your TypeScript code:
addNewItem(event: MouseEvent) { // Exit early if the clicked element isn't the parent div if (event.target !== event.currentTarget) { return; } // Your existing logic to add the new li item this.items.push(`New Item ${this.items.length + 1}`); }
This way, the add logic only runs when you click the parent directly.
3. Stop Event Propagation (Use With Caution)
You could also call event.stopPropagation() in the handler, but be careful with this—it prevents the event from reaching any parent elements above your target, which might break other functionality if you have nested click events elsewhere.
If you still want to use it, here's how:
addNewItem(event: MouseEvent) { event.stopPropagation(); // Only run the add logic if we're clicking the parent if (event.target === event.currentTarget) { this.items.push(`New Item ${this.items.length + 1}`); } }
Pick the method that fits your use case best—most of the time, the self modifier is the cleanest and quickest solution.
内容的提问来源于stack exchange,提问作者Idris

