Dale
Dale

Reputation: 619

Angular 4 - Printing a unique and dynamic value on an HTML with Angular's *ngFor

So i am presented with a task from the client to make a loop of div elements draggable. To make this happened, i have used angular2-draggable to make it possible.

It works on a single div that has not been looped over, as seen below:

<div ngDraggable [handle]="DemoHandle" class="card">
  <div #DemoHandle class="card-header">I'm handle. Drag me!</div>
  <div class="card-block">You can't drag this block now!</div>
</div>

But the question is, how to i make take this code an place it into an *ngFor loop in Angular (maybe just like the code seen below)?

<div *ngFor="let myValue of myValues" [handle]="{{myValue.id}}">
   <div #{{ myValue.id }} >{{ myValue.title }}</div>
</div>

The problem here is that both this [handle]="DemoHandle" and #DemoHandle (Im talking about the DemoHandle value) needs to be unique. But i have no way to print a unique value similar to this code below:

<div *ngFor="let myValue of myValues">
   <div [attr.id]="myValue.id" >{{ myValue.title }}</div>
</div>

How do i go about this?

Upvotes: 0

Views: 1191

Answers (1)

yurzui
yurzui

Reputation: 214017

Template reference variables are unique within enclosed view. *ngFor directive create embedded view for each item so that template reference variable is unique there.

So just try the following:

<div ngDraggable *ngFor="let item of [1,2,3]" [handle]="DemoHandle">
  <div #DemoHandle class="card-header">I'm handle {{item}}. Drag me!</div>
  ...
</div>

Ng-run Example

Upvotes: 1

Related Questions