【问题标题】:angular4 click doesn't work on div with ngIfangular4 click 不适用于带有 ngIf 的 div
【发布时间】:2018-01-26 06:33:19
【问题描述】:

我正在尝试将点击事件添加到 div。此 div 包含另一个由 ngIf 在布尔值上生成的 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);
  }
}

【问题讨论】:

    标签: html css angular


    【解决方案1】:

    您不需要为鼠标相关的 DOM 事件定义自定义事件发射器。

    您的组件的用户可以处理单击、鼠标悬停或鼠标悬停事件:

    HTML

    <usp-cell (click)="onClick($event)" 
         (mouseover)="onMouseOver($event)" 
         (mouseout)="onMouseOut($event)"></usp-cell>
    

    如果你想让组件usp-cell处理事件,因为它需要做一些事情,那么你可以使用@HostListener

    @HostListener('click', ['$event.target']) onClick(cell) {
       ...
    }
    

    【讨论】:

    • 感谢您的快速回答,但这无济于事。看起来内部 div(由 ngIf 生成)阻止了单击,只有当我单击外部 div 的边框时才会引发单击事件
    • @user3800293 - 那么你的 DOM 架构设计得不好。解决问题的暴力方法是阻止父级上的鼠标事件并允许子级上的鼠标事件。你可以用css来做。在父节点上,使用指针事件:无,在子节点上使用指针事件:全部 ...
    • @Emocuc 我知道我的架构有问题,但不知道如何解决。我有一个包含其他元素的 div。如果鼠标向下或向上,内容会有所不同。我需要所有的 div 都是可点击的。我该如何实现它?
    • @user3800293 - 最好在编码之前考虑应用程序,创建线框,用例,图形模型......并根据整体应用程序功能决定应用程序的编码方式。 ..从您的sn-p或评论中,我无法为您提供任何建议,我想您必须努力学习...
    【解决方案2】:

    HTML 元素事件以冒泡方式工作,这意味着它们会从子级传播到父级,但不会以其他方式传播。因此,如果您的父 div 有该事件,则孩子将没有它。检查这个例子:

    <div (click)="test()" style="background-color: #b30000; height: 150px">
      <div style="background-color: #00CC9B; height: 10px">
      </div>
    </div> 
    

    在这种情况下,只有父 div 会调用 test 函数,尽管事实上另一个 div 包含在其中。

    【讨论】:

    • 我不知道。我怎样才能给他们这个活动?
    【解决方案3】:

    找到问题了,虽然我不是很明白。 布尔值根据 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>
    

    【讨论】:

      猜你喜欢
      • 2013-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-09
      • 2022-11-25
      相关资源
      最近更新 更多