我正在尝试将click事件添加到div。这个div包含另一个由ngIf on Boolean生成的div,我得到它作为输入。 在这种情况下,事件不起作用,仅在外部div的边界上。 这是html:
<div class="cell-content-wrapper" (mouseover)="over()" (mouseout)="out()" (click)="openModal()">
<div *ngIf="myInput" class="cell-content" [ngClass]="[cell.action]">
<span class="tf {{ (cell.action | actionToIcon) }} cell-icon"></span>
</div>
</div>
这是组件:
@Component({
selector: 'usp-cell',
templateUrl: './usp-cell.component.html',
styleUrls: ['./usp-cell.component.scss']
})
export class UspCellComponent implements OnInit, OnChanges {
@Input() cell:;
@Input() myInput: boolean;
@Output() onClick: EventEmitter<UspCell> = new EventEmitter<>();
@Output() onMouseOver: EventEmitter<UspCell> = new EventEmitter<>();
@Output() onMouseOut: EventEmitter<UspCell> = new EventEmitter<>();
over() {
this.onMouseOver.emit(this.cell);
}
out() {
this.onMouseOut.emit(this.cell);
}
openModal() {
this.onClick.emit(this.cell);
}
}
答案 0 :(得分:2)
您不需要为与鼠标相关的DOM事件定义自定义事件发射器。
组件的用户可以处理click,mouseover或mouseout事件:
HTML
<usp-cell (click)="onClick($event)"
(mouseover)="onMouseOver($event)"
(mouseout)="onMouseOut($event)"></usp-cell>
如果您希望组件usp-cell
处理该事件,因为它需要执行某些操作,那么您可以使用@HostListener
@HostListener('click', ['$event.target']) onClick(cell) {
...
}
答案 1 :(得分:0)
HTML元素事件起泡,这意味着它们会从子节点传播到父节点,但不会以其他方式传播。因此,如果您的父div有事件,孩子就不会拥有它。检查此示例:
<div (click)="test()" style="background-color: #b30000; height: 150px">
<div style="background-color: #00CC9B; height: 10px">
</div>
</div>
在这种情况下,只有父div才会调用测试函数,尽管另一个包含在其中。
答案 2 :(得分:0)
<div class="cell-content-wrapper" (mouseover)="over()" (mouseout)="out()" (click)="openModal()">
<div class="cell-content" [ngClass]="[cell.action]">
<div *ngIf="myInput" ....>
....
</div>
<div *ngIf="!myInput" ....>
....
</div>
</div>
</div>