angular4 click对于带有ngIf的div不起作用

时间:2018-01-26 06:33:19

标签: html css angular

我正在尝试将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);
  }
}

3 个答案:

答案 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)

发现问题,即使我不太了解它。 布尔值根据mouseDown事件而改变。如果鼠标是向下的,那么应该出现div a,否则,将出现div B.所以当我点击时有两个不同的元素。这是修复

<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>