【问题标题】:angular2 template div on click check if element has classangular2模板div点击检查元素是否有类
【发布时间】:2016-09-19 13:55:25
【问题描述】:

我目前有一些逻辑,如果可能的话,我想在(点击)上仅使用 html 模板进行简化

我有一个可折叠的 div,点击后会变为“活动”

目前我的 div 是:

<div class="collapsible-header blue darken-2" (click)="getDataForTable($event)">

然后我正在检查元素上的类列表

function getDataForTable($event: any){
  let classList = $event.target.classList;

  if(classList.contains("active")){
  //do nothing div is closing
  } else {
  //get data for table since we are opening the div to show the body
  }
}

我希望这个 (click) 动作仅在类不是“活动”时触发 (意思是当点击为“活动”时不触发);

如何仅使用模板语法来做到这一点?

【问题讨论】:

  • 那么问题出在哪里?您是否尝试在 else-branch 中添加活动类?
  • 它有效,但我想知道我是否可以仅在模板上使用逻辑,以便 (click) 事件仅在其当前未“活动”时触发,而不是触发每次点击的函数我检查事件是否处于活动状态

标签: angular


【解决方案1】:
<div #mydiv 
    class="collapsible-header blue darken-2"    
    (click)="mydiv.classList.contains('xxx') ? getDataForTable($event) : null">

【讨论】:

    【解决方案2】:

    你应该可以这样做:

    <div class="collapsible-header blue darken-2" 
         (click)="$event.target.classList.contains('active') || getDataForTable($event)">
    

    然后在函数中你只需要添加类:

    function getDataForTable($event: any) {
      $event.target.classList.add('active');
      // get data for table since we are opening the div to show the body
    }
    

    【讨论】:

      猜你喜欢
      • 2016-10-27
      • 1970-01-01
      • 1970-01-01
      • 2011-09-25
      • 1970-01-01
      • 2011-08-03
      • 2015-01-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多