George Edwards George Edwards - 3 months ago 28
TypeScript Question

Referencing individual generated components from ngFor

I have an angular2 component which I have included below. I generate a list of

chapters
which I then display with an
*ngFor=
tag, but I want to be able to individually target these in my ng2 component (so I can highlight the selected chapter). I would of thought the below code would generate something like this:

<p class="chapter 1" #1>1. My First Chapter</p>


However, I don't get the #1, hence my selector doesn't work and I can't by default set the first chapter in the list to be selected.

import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';

@Component({
selector: 'tutorial',
template: `
<div class="content row">
<div class="chapters col s3">
<h3>Chapters:</h3>
<p *ngFor="let chapter of chapters" class="chapter" #{{chapter.number}}>{{chapter.number}}. {{chapter.title}}</p>
</div>
</div>
`
})
export class bookComponent implements AfterViewInit {
public chapters = _chapters;
@ViewChild('2') el:ElementRef;

ngAfterViewInit() {
this.el.nativeElement.className += " clicked";
}
}


What should I do to be able to individually select my generated
<p>
tags?

Answer

For you use case this might be a more angulary way

<p *ngFor="let chapter of chapters; let i=index" (click)="clickedItem = i" [class.clicked]="i == clickedItem" class="chapter" #{{chapter.number}}>{{chapter.number}}. {{chapter.title}}</p>
export class bookComponent implements AfterViewInit {
  public chapters = _chapters;
  clickedItem: number;
}

Updating the model and binding the view to make Angular reflect the model to the view is the preferred way instead of imperatively modifying the DOM.

Comments