我有一个基于 Angular 应用程序(当前为 v4.4)。我有一个 View ,其中一个组件显示其自身的实例有限次数,然后在最低的“子”组件中,有一个 svg。
我希望能够使用 (click)
事件获取已单击的最低组件。我认为我可以设置 z-index 来链接到迭代编号,以便每个后续子组件都出现在其父组件之上,因此当单击该区域中的任何位置时,都会触发正确的事件。
我做了这个demo在 plunkr 上。您将看到,单击 svg 不会触发 clicked 事件,但单击框内的任何其他区域,会引发该框及其所有父框的 clicked 事件。
我希望能够独立切换所有框的背景颜色。
这是我拥有的组件:
@Component({
selector: 'my-app',
template: `
<div>
<h2>Hello {{name}}</h2>
<my-child [iteration]="0"></my-child>
</div>
`,
})
export class App {
name:string;
constructor() {
this.name = `Angular! v${VERSION.full}`
}
}
@Component({
selector: 'my-child',
template: `
<div class="border" [style.background]="toggle ? 'green' : 'pink'" (click)="clicked()">
{{iteration}}
<my-child [iteration]="iteration" *ngIf="iteration < 3"></my-child>
<object *ngIf="iteration == 3"
id="img" width="300" height="300"
data="http://snapsvg.io/assets/images/logo.svg"></object>
</div>
`,
})
export class Child {
name:string;
@Input() iteration;
toggle: boolean;
constructor() {
this.name = `Angular! v${VERSION.full}`
this.toggle = false;
}
ngOnInit() {
++this.iteration;
}
clicked(){
this.toggle = !this.toggle;
console.log(this.iteration)
}
}
更新:
当前答案回答了这个问题的第一部分,但不处理 svg 单击,不触发显示 svg 的组件的单击事件。
最佳答案
我成功地用你的笨蛋做到了。您必须在 cliked 函数顶部使用 event.stopPropagation() ,但您还必须在点击操作中添加 $event ,如下所示:
在你的html中你必须有
(click)=clicked($event)
在 your.ts 中添加 stopPropagation :
clicked(event) {
event.stopPropagation();
}
编辑: 最后一层的解决方案是在 svg 元素顶部使用不可见的 div,您可能需要调整样式或位置。
<div style="width:300px; height:300px; position:absolute; z-index:1000">
</div>
<object *ngIf="iteration == 3"
id="img" width="300" height="300"
data="http://snapsvg.io/assets/images/logo.svg">
</object>
关于javascript - 单击子组件而不触发父组件上的单击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46987756/