Angular2学习教程之组件中的DOM操作详解


Posted in Javascript onMay 28, 2017

前言

有时不得不面对一些需要在组件中直接操作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元素后,可以采用类似的方式处理。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家三水点靠木的支持。

Javascript 相关文章推荐
javascript之Partial Application学习
Jan 10 Javascript
javascript学习笔记--数字格式类型
May 22 Javascript
avascript中的自执行匿名函数应用示例
Sep 15 Javascript
使用jQuery仿苹果官网焦点图特效
Dec 23 Javascript
js倒计时抢购实例
Dec 20 Javascript
jQuery实现网页顶部固定导航效果代码
Dec 24 Javascript
AngularJS 使用$sce控制代码安全检查
Jan 05 Javascript
jQuery实现本地预览上传图片功能
Jan 08 Javascript
JavaScript 节流函数 Throttle 详解
Jul 04 Javascript
mint-ui的search组件在键盘显示搜索按钮的实现方法
Oct 27 Javascript
react中使用swiper的具体方法
May 15 Javascript
微信小程序实现的3d轮播图效果示例【基于swiper组件】
Dec 11 Javascript
Angular2学习教程之ng中变更检测问题详解
May 28 #Javascript
Angular2使用jQuery的方法教程
May 28 #jQuery
Angular.js实现动态加载组件详解
May 28 #Javascript
利用node.js如何搭建一个简易的即时响应服务器
May 28 #Javascript
利用Angular.js编写公共提示模块的方法教程
May 28 #Javascript
Angular2入门教程之模块和组件详解
May 28 #Javascript
关于Angular2 + node接口调试的解决方案
May 28 #Javascript
You might like
新手学PHP之数据库操作详解及乱码解决!
2007/01/02 PHP
PHP数据库链接类(PDO+Access)实例分享
2013/12/05 PHP
解决PhpMyAdmin中导入2M以上大文件限制的方法分享
2014/06/06 PHP
php使用Image Magick将PDF文件转换为JPG文件的方法
2015/04/01 PHP
PHP自动识别当前使用移动终端
2018/05/21 PHP
使用laravel根据用户类型来显示或隐藏字段
2019/10/17 PHP
alixixi runcode.asp的代码不错的应用
2007/08/08 Javascript
javascript ie6兼容position:fixed实现思路
2013/04/01 Javascript
JS实现仿百度输入框自动匹配功能的示例代码
2014/02/19 Javascript
浅谈jquery.fn.extend与jquery.extend区别
2015/07/13 Javascript
AngularJS实现在ng-Options加上index的解决方法
2016/11/03 Javascript
angular实现商品筛选功能
2017/02/01 Javascript
微信小程序 滚动到某个位置添加class效果实现代码
2017/04/19 Javascript
vue.js实现用户评论、登录、注册、及修改信息功能
2020/05/30 Javascript
vue.js默认路由不加载linkActiveClass问题的解决方法
2017/12/11 Javascript
vue 本地服务不能被外部IP访问的完美解决方法
2018/10/29 Javascript
Node 代理访问的实现
2019/09/19 Javascript
node.js域名解析实现方法详解
2019/11/05 Javascript
JavaScript自定义超时API代码实例
2020/04/30 Javascript
[01:12:27]EG vs Secret 2018国际邀请赛淘汰赛BO3 第二场 8.22
2018/08/23 DOTA
[03:55]TI9战队采访——TNC Predator
2019/08/22 DOTA
Python简单实现TCP包发送十六进制数据的方法
2016/04/16 Python
在VS Code上搭建Python开发环境的方法
2018/04/06 Python
Python Django框架实现应用添加logging日志操作示例
2019/05/17 Python
利用CSS3实现文本框的清除按钮相关的一些效果
2015/06/23 HTML / CSS
Charlotte Tilbury美国官网:英国美妆品牌
2017/10/13 全球购物
史蒂夫·马登加拿大官网:Steve Madden加拿大
2017/11/18 全球购物
欧尚俄罗斯网上超市:Auchan俄罗斯
2018/05/03 全球购物
澳大利亚最早和最古老的巨型游戏专家:Yardgames
2020/02/20 全球购物
写一个在SQL Server创建表的SQL语句
2012/03/10 面试题
心理健康心得体会
2014/01/02 职场文书
群众路线教育实践活动心得体会(四风)
2014/11/03 职场文书
初中毕业生感言
2015/07/31 职场文书
中秋节感想
2015/08/10 职场文书
安全生产协议书
2016/03/22 职场文书
python如何获取网络数据
2021/04/11 Python