来自component.ts的* ngFor访问元素

时间:2018-07-24 04:52:18

标签: javascript angular typescript

所以我正在使用angular2-swing库,并且我的模板中包含以下代码:

  <ul class="stack" swing-stack  [stackConfig]="stackConfig"  #myswing1 (throwout)="onThrowOut($event)">
    <li swing-card #restaurantCards [ngClass]="restaurant.restaurant" *ngFor="let restaurant of restaurants">

      <app-restaurant-card [restaurant]=restaurant.restaurant>
      </app-restaurant-card>
      <div class="overlay">
        YUM!
      </div>  
    </li>
  </ul>

这是onThrowOut($event)方法:

onThrowOut(event: ThrowEvent) {

    if(event.throwDirection == Direction.RIGHT){
      this.restaurantService.addToLikes(event.target.getAttribute('ngClass'))
    }
    //make element hidden once thrown out
    event.target.setAttribute("style", "visibility: hidden; transition: .1s; ");
  }

但是,当我尝试获取属性时,它为null。有什么方法可以从for循环中检索元素吗?谢谢

1 个答案:

答案 0 :(得分:0)

可以在DOM中访问

ngClass class。将代码修改为(使用event.target.getAttribute('class')):

onThrowOut(event: ThrowEvent) {

  if(event.throwDirection == Direction.RIGHT){
    this.restaurantService.addToLikes(event.target.getAttribute('class'));
  }
  ...
}

还要注意,现在id将是string,所以可能您需要将它们转换为number