Angular2学习教程之组件中的DOM操作详解
前端之家收集整理的这篇文章主要介绍了
Angular2学习教程之组件中的DOM操作详解,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_4040@前言
@H
404_0@有时不得不面对一些需要在组件中直接操作DOM的情况,如我们的组件中存在大量的Check
Box,我们想
获取到被选中的Check
Box,然而这些Check
Box是通过循环产生的,我们无法给每一个Check
Box指定一个ID,这个时候可以通过操作DOM来实现。angular API中包含有viewChild,contentChild等修饰符,这些修饰符可以返回模板中的DOM元素。
@H_
404_0@
指令中的DOM操作
<div class="jb51code">
<pre class="brush:js;">
@Directive({
selector: 'p'
})
export class TodoDirective{
constructor(el: ElementRef,renderer: Renderer){
renderer.setElementStyle(el.nativeElement,'backgroundColor','red');
}
}
@H_
404_0@以上声明了一个指令,使用是需要在module中的declarations中声明。该指令的作用是将p元素的backgroundColor设置为red。
@H_
404_0@-ElementRef是一个允许直接
获取DOM元素的一个类,该类包含一个nativeElement
属性。当不允许直接操作原生DOM元素时,该
属性值为null。
@H_
404_0@-Renderer该类包含大量可以用来操作DOM原生的
方法。
@H_
404_0@
@ViewChild和@ViewChildren
@H_
404_0@每一个组件都有一个视图模板,通过 template或templateUrl引入。想要
获取视图模板中的DOM元素则可以使用@ViewChild和@ViewChildren修饰符。他们可以接受模板变量或元素
标签或模板类名来
获取DOM节点。@ViewChild返回ElementRef类引用(
获取组件时则直接使用组件类名),而@ViewChildren返回
QueryList
。
内容
{{ item.name }}
//组件中获取DOM
@ViewChildren('name')
todoNames: QueryList;
@ViewChild('name')
todoName: ElementRef;
ngAfterViewInit(){
this.todoNames.forEach(e=>console.log(e.nativeElement.innerText));
console.log(this.todoName.nativeElement.innerText);
}
@H_
404_0@
@ViewChild('name')和@ViewChildren('name')
通过name模板变量
获取p
标签DOM节点,可以在ngAfterViewInit声明周期钩子中
获取节点信息,当然也可以在其他
函数中,只要保证视图完成初始化即可。
@H_
404_0@QueryList是一个不可变的列表,其存在一个名为changes的Observable变量,因此可以被
订阅,结合notifyOnChanges
方法,可以实时查看QueryList中变量的变化。
调用notifyOnChanges
函数后,当组件的输入发生变化时会触发Observable发出新的值,这样当
todoNames: QueryList
有更新时,便能通过下面
代码查看到变化:
data._results.forEach(
e=>console.log(e.nativeElement.innerText)));
this.todoNames.notifyOnChanges();
@H_
404_0@
@ContentChild和@ContentChildren
@H_
404_0@看着与@ViewChild和@ViewChildren很相似,但@ContentChild和@ContentChildren是
获取组件
标签中的
内容的,懒得写例子,这里直接贴上angular
中文官网的一个例子:
panes: {{serializedPanes}}
`
})
export class Tab {
@ContentChildren(Pane) panes: QueryList
;
get serializedPanes(): string { return this.panes ? this.panes.map(p => p.id).join(',') : ''; }
}
@Component({
selector: 'example-app',template: `