无奈接手了一个旧项目,上一个老哥在Angular项目中大量使用了JQuery来操作DOM,真的是太不讲究了。那么如何优雅的使用Angular的方式来操作DOM呢?

获取元素

  1、ElementRef  ---   A wrapper around a native element inside of a View.

    在组件的 constructor中注入ElementRef,可以获取到整个组件元素的包裹。

@Component({
selector: 'app-test-page',
templateUrl: './test-page.component.html',
styleUrls: ['./test-page.component.scss']
})
export class TestPageComponent implements OnInit { constructor(
private el: ElementRef
) { } ngOnInit() {
} getDomTest() {
console.dir(this.el);
}

  ElementRef中的nativeElement即是组件最外层的DOM元素。再通过原生的DOM定位方式,即可获取到指定的selector元素。

  getDomTest() {
console.dir(this.el.nativeElement.querySelector('.test-get-dom')); // 获取指定的子元素
}

  

  2、@viewChild()  ---    You can use ViewChild to get the first element or the directive matching the selector from the  view DOM.

    @viewChild可以获取指定的元素, 指定的方式可以是本地变量或者组件类型;

// HTML
<div class="tip-test-wrapper">
   // 本地变量绑定button按钮
<button class="test-get-dom" #testdom (click)="getDomTest()">测试获取DOM</button>
</div>
  // Dialog组件
<app-dialog></app-dialog> // ts
import { DialogComponent } from './../../common/components/dialog/dialog.component'; @Component({
selector: 'app-test-page',
templateUrl: './test-page.component.html',
styleUrls: ['./test-page.component.scss']
})
export class TestPageComponent implements OnInit {
  // 通过本地变量获取元素 可通过read来指定获取的元素类型
@ViewChild('testdom' , { read: ViewContainerRef }) viewcontainer: ViewContainerRef;
@ViewChild('testdom') viewelement: ElementRef;   // 通过组件类型来获取
@ViewChild(DialogComponent) viewcontent: DialogComponent; constructor(
private el: ElementRef
) { } ngOnInit() {
} getDomTest() {
// console.dir(this.el.nativeElement.querySelector('.test-get-dom'));
console.dir(this.viewcontainer);
console.dir(this.viewelement);
console.dir(this.viewcontent);
}
}

  

  备注:ElementRef或者 @viewChild 获取元素,一定要在 ngAfterViewInit 周期之后再使用。

 3、@viewChildren --   You can use ViewChildren to get the {@link QueryList} of elements or directives from theview DOM.

  @viewChild会返回符合条件的第一个元素,如果需要获取多个符合条件的元素呢?@viewChildren会返回所有符合条件的元素的list。指定selector的方式与@viewChild一致。

// 复制一个元素
<div class="tip-test-wrapper">
<button class="test-get-dom" #testdom (click)="getDomTest()">测试获取DOM</button>
</div>
<div class="tip-test-wrapper">
<button class="test-get-dom" #testdom (click)="getDomTest()">测试获取DOM</button>
</div>
</div>
<app-dialog></app-dialog>
<app-dialog></app-dialog> // ts
import { DialogComponent } from './../../common/components/dialog/dialog.component'; @Component({
selector: 'app-test-page',
templateUrl: './test-page.component.html',
styleUrls: ['./test-page.component.scss']
})
export class TestPageComponent implements OnInit { @ViewChild('testdom' , { read: ViewContainerRef }) viewcontainer: ViewContainerRef;
@ViewChild('testdom') viewelement: ElementRef;
@ViewChildren('testdom') viewelements: QueryList<any>;
  @ViewChild(DialogComponent) viewcontent: DialogComponent;
@ViewChildren(DialogComponent) viewcontents: QueryList<DialogComponent>; constructor(
private el: ElementRef
) { } ngOnInit() {
} getDomTest() {
// console.dir(this.el.nativeElement.querySelector('.test-get-dom'));
// console.dir(this.viewcontainer);
console.dir(this.viewelement);
console.dir(this.viewelements);
console.dir(this.viewcontent);
console.dir(this.viewcontents);
}

  

操作DOM  --- Renderer2

  在获取dom之后,如何对dom进行操作呢?原生的domAPI是一种选择,但是Angular提供了更好的跨平台方式   Renderer2。

  引入 Renderer2  , 然后在construct中注入。

import { Component, OnInit , ViewContainerRef , ElementRef , ViewChild,  Renderer2 , ViewChildren, QueryList} from '@angular/core';

import { DialogComponent } from './../../common/components/dialog/dialog.component';

@Component({
selector: 'app-test-page',
templateUrl: './test-page.component.html',
styleUrls: ['./test-page.component.scss']
})
export class TestPageComponent implements OnInit { @ViewChild('testdom' , { read: ViewContainerRef }) viewcontainer: ViewContainerRef;
@ViewChild('testdom') viewelement: ElementRef;
@ViewChildren('testdom') viewelements: QueryList<any>;
@ViewChild(DialogComponent) viewcontent: DialogComponent;
@ViewChildren(DialogComponent) viewcontents: QueryList<DialogComponent>; constructor(
private render: Renderer2,
private el: ElementRef
) { } ngOnInit() {
} getDomTest() {
// 修改元素颜色
this.render.setStyle(this.viewelement.nativeElement , 'color' , 'red');
}

  renderer2提供了丰富的API供使用,如下:

总结

  通过elementRef或者@viewChild @viewChildren获取元素,再通过renderer2提供的API来操作元素。不过记得在不要在 ngAfterViewInit 周期之前使用。通过Angular提供的方式,可以满足大部分的操作DOM的需求了。如果有特殊的场景,当然还是原生DOM撸起来呀

Angular使用总结 --- 如何正确的操作DOM的更多相关文章

  1. Angular开发实践(七): 跨平台操作DOM及渲染器Renderer2

    在<Angular开发实践(六):服务端渲染>这篇文章的最后,我们也提到了在服务端渲染中需要牢记的几件事件,其中就包括不要使用window. document. navigator等浏览器 ...

  2. 框架操作DOM和原生js操作DOM比较

    问题引出 对于Angular和React操作DOM的速度,和原生js操作DOM的速度进行了一个比较: 一个同学做的demo 代码如下: <!DOCTYPE html> <html n ...

  3. JavaScript操作DOM的那些坑

    js在操作DOM中存在着许多跨浏览器方面的坑,本文花了我将近一周的时间整理,我将根据实例整理那些大大小小的“坑”. DOM的工作模式是:先加载文档的静态内容.再以动态方式对它们进行刷新,动态刷新不影响 ...

  4. JavaScript 节点操作Dom属性和方法(转)

    JavaScript 节点操作Dom属性和方法   一些常用的dom属性和方法,列出来作为手册用. 属性:   1.Attributes 存储节点的属性列表(只读)   2.childNodes 存储 ...

  5. 怎么在ng-repeat生成的元素上操作dom

    这个问题其实对初学者来说,都 有这样的经历,用ng-repeat生成的元素用js怎么也获取不到;这个其中原由是:angular拥有自动化渲染DOM的特性,它能帮助我们专注于操作数据,而页面的渲染则由a ...

  6. jQuery框架-2.jQuery操作DOM节点与jQuery.ajax方法

    一.jQuery操作DOM 内部插入操作: append(content|fn):向每个匹配的元素内部追加内容. prepend(content):向每个匹配的元素内部前置内容. 外部插入操作: af ...

  7. 你所不了解的javascript操作DOM的细节知识点(一)

    你所不了解的javascript操作DOM的细节知识点(一) 一:Node类型 DOM1级定义了一个Node接口,该接口是由DOM中的所有节点类型实现.每个节点都有一个nodeType属性,用于表明节 ...

  8. JQuery制作网页—— 第三章 JavaScript操作DOM对象

    1. DOM:Document Object Model(文档对象模型):          DOM操作:                   ●DOM是Document Object Model的缩 ...

  9. 前端性能优化--为什么DOM操作慢? 浅谈DOM的操作以及性能优化问题-重绘重排 为什么要减少DOM操作 为什么要减少操作DOM

    前端性能优化--为什么DOM操作慢?   作为一个前端,不能不考虑性能问题.对于大多数前端来说,性能优化的方法可能包括以下这些: 减少HTTP请求(合并css.js,雪碧图/base64图片) 压缩( ...

随机推荐

  1. 为什么要使用mybaits

    通常在项目开发过程中,有很多代码是重复的,固定不变的.为了提升开发效率,可将这些 固定不变的代码提取出来,生成class文件,将class文件打jar包,基于框架开发. mybaits是一个ORM框架 ...

  2. poj 2349 求最小生成树里面第m长的边

    题目链接:https://vjudge.net/problem/POJ-2349 题意: 题目就是要我们找到一个最小的值D,把图里面所有大于D的边去掉之后剩余的连通分支的数量为S.这个就是找这个图里面 ...

  3. 堆优化dij

    #include<iostream> #include<cstdio> #include<queue> using namespace std; ],head[], ...

  4. 652. Find Duplicate Subtrees找出重复的子树

    [抄题]: 就是出现了多次的子树,可以只包括一个点. Given a binary tree, return all duplicate subtrees. For each kind of dupl ...

  5. 【转载】我为什么弃用OpenStack转向VMware vsphere

    我为什么弃用OpenStack转向VMware Vsphere,一切皆为简单.高效.因为我们在工作过程中涉及到大量的测试工作,每天都有成百个虚拟机的创建和销毁工作. 工作任务非常繁重,我们的持续集成平 ...

  6. java【基础】多态

    new 接口就会发生很有意思的现象 public class InerClassDemo { public static void main(String[] args) { // TODO Auto ...

  7. python 去除字符串末尾的子串

    建议使用 "字符串".replace("要去除的字符串", "") 尽量不要使用 strip() ,有时会引入意想不到的结果.strip() ...

  8. c++沉思录 学习笔记 第五章 代理类

    Vehicle 一个车辆的虚基类 class Vehicle {public: virtual double weight()const = 0; virtual void start() = 0; ...

  9. SpringBoot小新手。

    2018-09-27 最近在学习SpringBoot:教材 先是在https://start.spring.io/下载了工程.demo.zip 下载之后,导入Eclipse工程,pom.xml里面的& ...

  10. UVA 2451 Brackets sequence

    题目链接:https://icpcarchive.ecs.baylor.edu/index.php?option=com_onlinejudge&Itemid=8&category=9 ...