Angular2学习笔记-组件中的DOM操作

有时不得不面对一些需要在组件中直接操作DOM的情况,如我们的组件中存在大量的CheckBox,我们想获取到被选中的CheckBox,然而这些CheckBox是通过循环产生的,我们无法给每一个CheckBox指定一个ID,这个时候可以通过操作DOM来实现。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节点。@ViewChild返回ElementRef类引用(获取组件时则直接使用组件类名),而@ViewChildren返回QueryList<ElementRef>。

//模板内容
<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节点,可以在ngAfterViewInit声明周期钩子中获取节点信息,当然也可以在其他函数中,只要保证视图完成初始化即可。

QueryList是一个不可变的列表,其存在一个名为changes的Observable变量,因此可以被订阅,结合notifyOnChanges方法,可以实时查看QueryList中变量的变化。调用notifyOnChanges函数后,当组件的输入发生变化时会触发Observable发出新的值,这样当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是获取组件标签中的内容的,懒得写例子,这里直接贴上angular中文官网的一个例子:

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中的内容:

 <tab>
      <pane id="1"></pane>
      <pane id="2"></pane>
      <pane id="3" *ngIf="shouldShow"></pane>
 </tab>

与@ViewChild类似@ContentChild获取的是第一个Pane指令,获取DOM元素后,可以采用类似的方式处理。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 指令定义 对于指令,可以把它简单的理解成在特定DOM元素上运行的函数,指令可以扩展这个元素的功能。  我们可以自己...
    oWSQo阅读 4,884评论 0 0
  • 组件基础 组件用来包装特定的功能,应用程序的有序运行依赖于组件之间的协同工作。组件是angular应用的最小逻辑单...
    oWSQo阅读 5,186评论 0 0
  • AngularJS是什么?AngularJs(后面就简称ng了)是一个用于设计动态web应用的结构框架。首先,它是...
    200813阅读 5,552评论 0 3
  • 你想干嘛?!偷东西?!一个戴眼镜的年轻人男人大叫。 顺着男人的目光,所有人的目光都集中到了这个带着帽子的中...
    藏之不借阅读 3,146评论 1 1
  • 亲爱的宝贝,时间过得好快,一转眼,今天是你正式进入小学的第十一天,也是妈妈第一次参加你小学一年级的家长会,也是妈妈...
    a慈阅读 3,214评论 0 0