Dom 从ngFor引用单个生成的组件
我有一个angular2组件,我已经包括在下面。我生成一个章节列表,然后用*ngFor=标记显示,但我希望能够在我的ng2组件中单独针对这些章节,以便突出显示所选章节。我认为下面的代码会生成如下内容:Dom 从ngFor引用单个生成的组件,dom,angular,typescript,Dom,Angular,Typescript,我有一个angular2组件,我已经包括在下面。我生成一个章节列表,然后用*ngFor=标记显示,但我希望能够在我的ng2组件中单独针对这些章节,以便突出显示所选章节。我认为下面的代码会生成如下内容: <p class="chapter 1" #1>1. My First Chapter</p> 但是,我没有得到1,因此我的选择器不起作用,默认情况下,我无法设置要选择的列表中的第一章 import { Component, ViewChild, ElementRef,
<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";
}
}
我应该怎么做才能单独选择生成的标记?我会让NgFor循环控制添加或删除单击的类: 您可以将指令与HostListener一起使用来选择一个元素,如下所示 工作演示:
对于您的用例,这可能是一种更具角度的方式
<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>
更新模型并绑定视图以使模型向视图进行角度反射是首选方法,而不是强制修改DOM
export class bookComponent {
public chapters = _chapters;
private selectedChapterNumber = 1;
}
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"}]
}
<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;
}