引用ngFor中的各个生成组件

时间:2016-08-09 16:04:09

标签: dom angular typescript

我有一个angular2组件,我在下面包含了它。我生成一个chapters列表,然后我用*ngFor=标签显示,但我希望能够在我的ng2组件中单独定位这些(所以我可以突出显示所选章节)。我想以下代码会生成这样的东西:

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

但是,我没有得到#1,因此我的选择器不起作用,我不能默认设置列表中的第一章来选择。

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

如何才能单独选择生成的<p>代码?

3 个答案:

答案 0 :(得分:1)

对于你的用例,这可能是一种更有棱角的方式

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

更新模型并绑定视图以使Angular将模型反映到视图是首选方式,而不是强制修改DOM。

答案 1 :(得分:0)

我会让NgFor循环控件添加或删除clicked类:

<p *ngFor="let chapter of chapters" class="chapter"
  [class.clicked]="chapter.number === selectedChapterNumber">
  {{chapter.number}}. {{chapter.title}}
</p>

然后只需在组件逻辑中正确设置selectedChapterNumber

export class bookComponent {
    public chapters = _chapters;
    private selectedChapterNumber = 1;
}

答案 2 :(得分:0)

您可以将指令与HostListener 一起使用到选择一个元素,如下所示。

工作演示:http://plnkr.co/edit/mtmCKg7kPgZoerqT0UIO?p=preview

import {Directive, Attribute,ElementRef,Renderer,Input,HostListener} from '@angular/core';

@Directive({
  selector: '[myAttr]'
})

export class myDir {
    constructor(private el:ElementRef,private rd: Renderer){
      console.log('fired');
      console.log(el.nativeElement); 
    }

    @HostListener('click', ['$event.target'])
    onClick(btn) {
      if(this.el.nativeElement.className=="selected"){
          this.el.nativeElement.className ="";  
      }else{
          this.el.nativeElement.className ="selected";
      }
   }
}
//our root app component
import {Component} from '@angular/core';

@Component({
  selector: 'my-app',
  directives:[myDir],
  template: 
  `
  <style>
    .selected{
      color:red;
      background:yellow;
    }
  </style>
    <div class="content row">
    <div class="chapters col s3">
        <h3>Chapters:</h3>
        <p myAttr *ngFor="let chapter of chapters" class="chapter" #{{chapter.number}}>{{chapter.number}}. {{chapter.title}}</p>
    </div>
</div>
  `
})
export class App {
  chapters=[{number:1,title:"chapter1"},{number:2,title:"chapter2"},{number:3,title:"chapter3"}]


}
相关问题