简体   繁体   中英

Access element of *ngFor from component.ts

So I'm using the angular2-swing library and I have the following code in my template:

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

Here is the onThrowOut($event) method:

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; ");
  }

However, when I try to get the attribute, it is null. Is there any way to retrieve the element from the for loop? Thanks

ngClass can be accessed class in DOM. Modify your code as (use event.target.getAttribute('class') ):

onThrowOut(event: ThrowEvent) {

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

Also note that, now id would be string so may be you need to convert them as number

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM