Angular2 Get reference to element created in ngFor

Viewed 38303

How would I go for referencing an Element in the dom which was created in a ngFor loop.

e.g. I have a list of elements which I iterate over:

var cookies: Cookie[] = [...];

<div *ngFor="#cookie of cookies" id="cookie-tab-button-{{cookie.id}}" (click)="showcookie(cookie);">Cookie tab</div>


<div *ngFor="#cookie of cookies" id="cookie-tab-content-{{cookie.id}}" ">Cookie Details</div>

How would I reference these divs, so I could add a css class like "is-active". Or is my approach just wrong.

5 Answers
<div *ngFor="let item of items" (click)="itemClick($event.currentTarget)"></div>

itemClick(dom){
  dom.style.color='red';
  // ...
}

Another variation:

In the parent control:

// typescript
childControls: ChildComponent[] = [];

<!-- HTML -->
<ng-container *ngFor='let period of periods'>
  <app-child [period]='period' [parent]='this'></app-child>
</ng-container>

In the child control:

private _parent: ParentComponent;
@Input() set parent(value: ParentComponent) {
  this._parent.childControls.push(this);
}
get parent(): ParentComponent {
  return this._parent;
}

This provides an array of references to the child controls in the parent.

Related