有時不得不面對一些需要在組件中直接操作DOM的情況稚茅,如我們的組件中存在大量的CheckBox,我們想獲取到被選中的CheckBox平斩,然而這些CheckBox是通過循環(huán)產(chǎn)生的亚享,我們無法給每一個CheckBox指定一個ID,這個時候可以通過操作DOM來實現(xiàn)绘面。angular API中包含有viewChild欺税,contentChild等修飾符,這些修飾符可以返回模板中的DOM元素揭璃。
指令中的DOM操作
@Directive({
selector: 'p'
})
export class TodoDirective{
constructor(el: ElementRef, renderer: Renderer){
renderer.setElementStyle(el.nativeElement, 'backgroundColor', 'red');
}
}
以上聲明了一個指令晚凿,使用是需要在module中的declarations中聲明。該指令的作用是將p元素的backgroundColor設置為red瘦馍。
-ElementRef是一個允許直接獲取DOM元素的一個類歼秽,該類包含一個nativeElement屬性。當不允許直接操作原生DOM元素時情组,該屬性值為null燥筷。
-Renderer該類包含大量可以用來操作DOM原生的方法。
@ViewChild和@ViewChildren
每一個組件都有一個視圖模板院崇,通過 template或templateUrl引入肆氓。想要獲取視圖模板中的DOM元素則可以使用@ViewChild和@ViewChildren修飾符。他們可以接受模板變量或元素標簽或模板類名來獲取DOM節(jié)點底瓣。@ViewChild返回ElementRef類引用(獲取組件時則直接使用組件類名)谢揪,而@ViewChildren返回QueryList<ElementRef>。
//模板內(nèi)容
<p *ngFor='let item of todos' #name>{{ item.name }}</p>
//組件中獲取DOM
@ViewChildren('name')
todoNames: QueryList<ElementRef>;
@ViewChild('name')
todoName: ElementRef;
ngAfterViewInit(){
this.todoNames.forEach(e=>console.log(e.nativeElement.innerText));
console.log(this.todoName.nativeElement.innerText);
}
@ViewChild('name')和@ViewChildren('name')通過name模板變量獲取p標簽DOM節(jié)點,可以在ngAfterViewInit聲明周期鉤子中獲取節(jié)點信息键耕,當然也可以在其他函數(shù)中寺滚,只要保證視圖完成初始化即可柑营。
QueryList是一個不可變的列表屈雄,其存在一個名為changes的Observable變量,因此可以被訂閱官套,結合notifyOnChanges方法酒奶,可以實時查看QueryList中變量的變化。調用notifyOnChanges函數(shù)后奶赔,當組件的輸入發(fā)生變化時會觸發(fā)Observable發(fā)出新的值惋嚎,這樣當todoNames: QueryList<ElementRef>
有更新時,便能通過下面代碼查看到變化:
this.todoNames.changes.subscribe(data => data._results.forEach(
e=>console.log(e.nativeElement.innerText)));
this.todoNames.notifyOnChanges();
@ContentChild和@ContentChildren
看著與@ViewChild和@ViewChildren很相似站刑,但@ContentChild和@ContentChildren是獲取組件標簽中的內(nèi)容的另伍,懶得寫例子,這里直接貼上angular中文官網(wǎng)的一個例子:
import {Component, ContentChildren, Directive, Input, QueryList} from '@angular/core';
@Directive({selector: 'pane'})
export class Pane {
@Input() id: string;
}
@Component({
selector: 'tab',
template: `
<div>panes: {{serializedPanes}}</div>
`
})
export class Tab {
@ContentChildren(Pane) panes: QueryList<Pane>;
get serializedPanes(): string { return this.panes ? this.panes.map(p => p.id).join(', ') : ''; }
}
@Component({
selector: 'example-app',
template: `
<tab>
<pane id="1"></pane>
<pane id="2"></pane>
<pane id="3" *ngIf="shouldShow"></pane>
</tab>
<button (click)="show()">Show 3</button>
`,
})
export class ContentChildrenComp {
shouldShow = false;
show() { this.shouldShow = true; }
}
可以看出@ContentChildren(Pane) panes: QueryList<Pane>;
獲取的是組件Tab中的內(nèi)容:
<tab>
<pane id="1"></pane>
<pane id="2"></pane>
<pane id="3" *ngIf="shouldShow"></pane>
</tab>
與@ViewChild類似@ContentChild獲取的是第一個Pane指令绞旅,獲取DOM元素后摆尝,可以采用類似的方式處理。