Angular Render2你了解吗?
Render2
介绍
Render2 是angular中用于操作dom的,Angular做了封装,屏蔽底层差异,通用性更强。不仅仅可以用于浏览器端,还可以用于Server Side rendering, Web-Worker, mobile apps, and desktop apps等。
Render2之指令用法
- setStyle、removeStyle
# 定义指令import { Directive, ElementRef, OnInit, Renderer2, HostListener } from '@angular/core';@Directive({ selector: '[animate]' })export class Animate {constructor(private renderer: Renderer2, private el: ElementRef) {}@HostListener('click') performTask() {let randomColor = "#"+((1<<24)*Math.random()|0).toString(16);this.renderer.setStyle(this.el.nativeElement, 'color', randomColor);this.renderer.setStyle(this.el.nativeElement, 'background-color', 'black'); this.renderer.removeStyle(this.el.nativeElement, 'color','red'); }}
# html
<h2 animate>Click here to give me a random color</h2>
- setAttribute、removeAttribute
@Directive({ selector: '[defaultValue]'
})
export class DefaultInputValueDirective {constructor(private elRef: ElementRef, private renderer: Renderer2) {}@HostListener('mouseover') onMouseOver() {this.renderer.setAttribute(this.elRef.nativeElement, 'value', 'Enter a Value');}@HostListener('mouseleave') onMouseLeave() {this.renderer.removeAttribute(this.elRef.nativeElement, 'value');}
}
- addClass、removeClass
@Directive({ selector: '[hlOnMouseOver]'
})
export class HlOnMouseOverDirective {constructor(private elRef: ElementRef, private renderer: Renderer2) {}@HostListener('mouseover') onMouseOver() {this.renderer.addClass(this.elRef.nativeElement, 'hl-text');}@HostListener('mouseleave') onMouseLeave() {this.renderer.removeClass(this.elRef.nativeElement, 'hl-text');}
}
- removeChild、appendChild
@Directive({ selector: '[removeChild]'
})
export class RemoveChildDirective {constructor(private elRef: ElementRef, private renderer: Renderer2) {}p = this.renderer.createElement('p');text = this.renderer.createText('Hello World !');@HostListener('mouseover') onMouseOver() {this.renderer.appendChild(this.p, this.text); this.renderer.appendChild(this.elRef.nativeElement, this.p);}@HostListener('mouseleave') onMouseLeave() {this.renderer.removeChild(this.elRef.nativeElement, this.p);}
}
- setProperty
@Directive({ selector: '[imgAlt]'
})
export class ImageAltdDirective {constructor(private renderer: Renderer2, private elRef: ElementRef) {}ngOnInit() {this.renderer.setProperty(this.elRef.nativeElement, 'alt', 'image description');}}
Render2之组件用法 - 大部分构造方法只有Renderer2
- viewChild操作dom appendChild
import { Component, ElementRef, Renderer2, ViewChild } from '@angular/core';@Component({selector: 'app-component',template: `<ul class="col-md-2"><li (click)="addBtn()" #addButton>Click here to add new button</li></ul> `
})export class AppComponent { @ViewChild('addButton') private animateThis: ElementRef; constructor(private renderer: Renderer2) {}addBtn() {const button = this.renderer.createElement('button'); const buttonText = this.renderer.createText('This is a button');this.renderer.appendChild(button, buttonText);this.renderer.appendChild(this.animateThis.nativeElement, button);}
}
# html
<ul class="col-md-2"><li (click)="addBtn()" #addButton>Click here to add new button</li>
</ul>
- insertBefore 、createComment
import { Component, ElementRef, Renderer2, ViewChild } from '@angular/core';@Component({selector: 'app-component',template: `<ul class="col-md-2"><li (click)="addBtn()" #addButton>Click here to add new button</li></ul> `
})export class AppComponent { @ViewChild('addButton') private animateThis: ElementRef; constructor(private elRef: ElementRef, private renderer: Renderer2) {}addBtn() {const button = this.renderer.createElement('button'); const buttonText = this.renderer.createText('This is a button');const comment = this.renderer.createComment('createComment? Comment Created!');const parent = this.elRef.nativeElement.parentNode;const reference = this.elRef.nativeElement;this.renderer.appendChild(button, buttonText);this.renderer.insertBefore(parent, comment, reference )this.renderer.appendChild(this.animateThis.nativeElement, button);}
}
- setStyle
import { Component, ViewChild, ElementRef, Renderer2 } from '@angular/core';@Component({selector: 'my-app',template: `Username: <input type="text" placeholder="type your name..." #changeStyle>`,
})
export class AppComponent {@ViewChild('changeStyle') private elRef: ElementRef; constructor(private renderer: Renderer2) {}ngOnInit() {this.renderer.setStyle(this.elRef.nativeElement, 'border', '1px solid red');}
}
- addClass
import { Component, ViewChild, ElementRef, Renderer2 } from '@angular/core';@Component({selector: 'my-app',template: `Username: <input type="text" placeholder="type your name..." #changeStyle>`,
})
export class AppComponent {@ViewChild('changeStyle') private elRef: ElementRef; constructor(private renderer: Renderer2) {}ngOnInit() {this.renderer.addClass(this.elRef.nativeElement, 'someClass');}//HTML output//<input placeholder="type your name..." type="text" class="someClass">
}
- setAttribute
import { Component, ViewChild, ElementRef, Renderer2 } from '@angular/core';@Component({selector: 'my-app',template: `Username: <input type="text" placeholder="type your name..." #changeStyle>`,
})
export class AppComponent {@ViewChild('changeStyle') private elRef: ElementRef; constructor(private renderer: Renderer2) {}ngOnInit() {this.renderer.setAttribute(this.elRef.nativeElement, 'value', 'Gokhan');}
}
- setProperty
import { Component, ViewChild, ElementRef, Renderer2 } from '@angular/core';@Component({selector: 'my-app',template: `Username: <input type="text" placeholder="type your name..." #changeStyle>`,
})
export class AppComponent {@ViewChild('changeStyle') private elRef: ElementRef; constructor(private renderer: Renderer2) {}ngOnInit() {this.renderer.setProperty(this.elRef.nativeElement, 'disabled', 'disabled');this.renderer.setProperty(this.elRef.nativeElement, 'innerHTML', change the inner html');}
}
- nextSibling
import { Component, Renderer2, ElementRef, ViewChild, OnInit } from '@angular/core';@Component({selector: 'my-app',template: `<p #next>First</p><p>Second</p><p>Third</p>`,styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {@ViewChild('next') private elRef: ElementRef; constructor(private renderer: Renderer2) {}ngOnInit(){const currentElement = this.elRef.nativeElement;const nextEl = this.renderer.nextSibling(currentElement);this.renderer.addClass(nextEl, 'red');}}
- parentNode
import { Component, Renderer2, ElementRef, ViewChild, OnInit } from '@angular/core';@Component({selector: 'my-app',template: `<div><p #parent>First</p><p>Second</p><p>Third</p></div>`,styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {@ViewChild('parent') private elRef: ElementRef; constructor(private renderer: Renderer2) {}ngOnInit(){const currentElement = this.elRef.nativeElement;const parent = this.renderer.parentNode(currentElement);this.renderer.addClass(parent, 'red');}}
- selectRootElement
# selectRootElement(selectorOrNode: any, preserveContent?: boolean) - 是否保留子内容import { Component, Renderer2, ElementRef, ViewChild, OnInit } from '@angular/core';@Component({selector: 'my-app',template: `<div #root>X or Y?</div> <button (click)="changeIt()">Click</button>`,styleUrls: [ './app.component.css' ]
})
export class AppComponent {switchText: boolean = false;@ViewChild('root') private elRef: ElementRef; constructor(private renderer: Renderer2) {}changeIt(){this.switchText = !this.switchText;const rootEl = this.elRef.nativeElement;const text = this.switchText ? this.renderer.createText('Hey X!') :this.renderer.createText('Hey Y!');this.renderer.selectRootElement(rootEl); this.renderer.appendChild(rootEl, text)}}
# 源码
selectRootElement(selector: string): Element {var el = DOM.querySelector(this._rootRenderer.document, selector);if (isBlank(el)) {throw new BaseException(`The selector "${selector}" did not match any elements`);}DOM.clearNodes(el);return el;}
- listen
import { Component, ViewChild, ElementRef, Renderer2 } from '@angular/core';@Component({selector: 'my-app',template: `<p #listen>Hover to see some magic!</p>{{count}}`,
})
export class AppComponent {@ViewChild('listen') private elRef: ElementRef; constructor(private renderer: Renderer2) {}toggle = false; count = 0; ngAfterViewInit() {this.renderer.listen(this.elRef.nativeElement, 'mouseover', () => {this.toggle = !this.toggle;this.count++;const currentElement = this.elRef.nativeElement;const firstText = this.renderer.createText('Hover to see new text! (Hover me)');const secondText = this.renderer.createText('Text changed! (Hover me)');const thirdText = this.renderer.createText('Reached maximum count!');this.renderer.selectRootElement(currentElement);if(this.count < 10){this.toggle ? this.renderer.appendChild(currentElement, secondText) : this.renderer.appendChild(currentElement, firstText);} else {this.renderer.appendChild(currentElement, thirdText);this.count = 10;}});}
}
参考
Angular Render2
Angular Render2你了解吗?相关推荐
- Angular Render2
Angular Render2 Renderer2类是Angular以service的形式提供的抽象,允许操作应用程序的元素而无需直接触摸DOM.这是推荐的方法,因为它可以更容易地开发可以在没有DOM ...
- Angular学习笔记64:使用Render2安全操作DOM元素
在项目中有时候需要直接操作DOM,但是这样直接访问 DOM 会导致应用很容易受到在 XSS 攻击.所以并不建议直接访问 DOM. 在Angular 访问DOM 需要使用 Render2 来实现自定义渲 ...
- angular组合preact
preact 大小3kb,可以当做angular的一个dom库,而且可以对接使用preact生态系统,react组件修改成preact还是蛮简单的,这样就可以解决angular中用render2操作d ...
- Angular No name was provided for external module 'XXX' in output.globals 错误
Angular 7 开发自定义库时,引用ngZorroAntd,build过程中出现 No name was provided for external module 'ng-zorro-antd' ...
- angular.isUndefined()
<!DOCTYPE html> <html><head><meta charset="UTF-8"><title>ang ...
- 五:Angular 数据绑定 (Data Binding)
通常来说,数据绑定要么是从页面流向组件中的数据,要么是从组件中的数据流向页面.下面我们来介绍在Angular 2中数据绑定的几种不同方式. 1. 使用{{}}将组件中的数据显示在html页面上 实 ...
- angular初步认识一
最近比较流行MVC前端框架开发,最近研究了一个框架AngularJS框架 不说那么多,先上例子,我是个代码控 <!DOCTYPE html> <html lang="en& ...
- 【讲人话】Angular如何通过@ViewChildren获取实时渲染的动态DOM节点元素(@ViewChild只能获取静态的固定DOM节点)
故事背景:有一天,强哥整了个动态渲染的列表代码如下 app.component.html <div><button (click)="add()">添加一行 ...
- Angular的ChangeDetectorRef.detectChanges()实现angularJS的$apply()方法,强制刷新数据渲染
在Javascript代码里,都是按照一定顺序来执行的,当轮到一个代码片段执行的时候,浏览器就只会去执行当前的片段,不会做任何其他的事情.所以有时候一些做得不是很好的网页,当点击了某个东西之后会卡住, ...
最新文章
- POJ3041 最小顶点覆盖
- Android多线程优劣,Android 开发中用到的几个多线程解析
- python数据显示为什么只能显示最后一个变量,Python变量和简单数据类型,之,的
- Anaconda下安装tensorflow-gpu踩坑日记
- Myeclipse下使用Maven搭建spring boot项目(第二篇)
- python导入requests库_windows环境中python导入requests
- python写dnf脚本怎么过检测_python写dnf脚本巡山和捉妖无病毒
- bat编程和vbs编程入门
- 免费ftp空间的文件传输
- 搜索引擎使用的10个技巧
- 【我们一起写框架】MVVM的WPF框架(一)—序篇
- xp开机黑屏故障分析
- 品牌和爱情,原理是一样的
- 阿里巴巴发布AliGenie 语音开放平台 “智联网”战略又落一子
- props写法_vue props default Array或是Object的正确写法说明
- GNU开发工具——WireShark网络分析工具
- 扫描器s-scan下载安装功能应用
- 核酸检测软件开发方案
- Jzoj4745 看电影
- 【JS笔记】JS中的DOM对象以及通过JS获取DOM结点,操作DOM属性、DOM增删改查